Show field only if user.is? :admin

1,286 views
Skip to first unread message

Gpx

unread,
Mar 8, 2012, 3:59:46 PM3/8/12
to rails_admin
Hello I'm building a small web site. Basically there are a User and a
Event models. The associations are User has_many :events and Event
belongs_to :user.
Every user can be a guest or an administrator. I've also have a method
user.is?(:role).
If a guest creates a new event it is automatically associated to it,
instead if an admin creates an event he can choose to associate it to
whoever he wants.

So I need to hide the user field if the current_user is a guest and
set its default value to current_user.id, but if the user is an admin
he can modify the field.

I've tried this https://github.com/sferik/rails_admin/wiki/How-to-set-default-values
but is not working for me because if I set the field as "visible
false" the value is no longer passed to the controller.

Someone knows how to solve my problem?

Thanks.

Benoit Bénézech

unread,
Mar 9, 2012, 5:44:43 AM3/9/12
to rails...@googlegroups.com
Add a hidden field.

field :my_field, :hidden do
  default_value do
    ..
  end
end

field :my_field_override do
  visible do 
    bindings[:user].role == :admin
  end
end

And then deal with my_field/my_field_override in your model.

Gpx

unread,
Mar 9, 2012, 6:29:11 AM3/9/12
to rails...@googlegroups.com
There isn't just a way to set the field as hidden only under a condition?

Benoit Bénézech

unread,
Mar 9, 2012, 7:33:54 AM3/9/12
to rails...@googlegroups.com
No. Because it depends on the field's class.

But you can hack the render method (and render the field conditionally).

Gpx

unread,
Mar 9, 2012, 8:20:02 AM3/9/12
to rails...@googlegroups.com
You mean something like

render do
  if bindings[:view]._current_user.is? :admin
    #something
  else
    #something else
  end
end

But I don't know what to put where there are the comments.

Benoit Bénézech

unread,
Mar 9, 2012, 9:18:30 AM3/9/12
to rails...@googlegroups.com
#1 Copy that line:

#2 Smtg like:

  bindings[:form].hidden_field(self.method_name, :value => self.value) + 
  self.pretty_value

Gpx

unread,
Mar 9, 2012, 10:33:29 AM3/9/12
to rails...@googlegroups.com
It works! Now I have only to figure out how to hide the label.
Thanks.

Benoit Bénézech

unread,
Mar 9, 2012, 10:44:42 AM3/9/12
to rails...@googlegroups.com
Yeah, you may need some JS targetting for that, since the outer CSS classes won't change and you can't control them at the moment.

Glauco Custódio

unread,
Nov 28, 2013, 8:15:29 AM11/28/13
to rails...@googlegroups.com, pol...@gmail.com
Reply all
Reply to author
Forward
0 new messages