Conditional Fields in Rails Admin

All we know that Rails Admin give us capability to restrict records through authorization, I have made a heavy use this feature, but sometimes we need to restrict a few fields in a given model through roles or something else. How could we get it?

Let's suppose we have a field called product_type in Product model, in our rails_admin initializer file we would have something like that:

config.model Product do
# ...
create do
field :name
field :product_type do
label 'Product Type'
end
end
end

This way, all users could be changing the product type, let's restrict this field now in order to just users with role master can be changing it:

config.model Product do
# ...
create do
field :name
field :product_type do
label do
if bindings[:view]._current_user.has_role? :master
'Product Type'
else
false
end
end
help false
render do
if bindings[:view]._current_user.has_role? :master
bindings[:view].render :partial => "rails_admin/main/#{partial}", :locals => {:field => self, :form => bindings[:form] }
else
''
end
end
end
end
end

In the render block is where the magic happens, if the condition is satisfied then we call the default behavior from Rails Admin that is here, otherwise we just return an empty string.

See you.

Written on November 28, 2013

Share: