In Rails guide in http://edgeguides.rubyonrails.org/security.html, section 6.1, it introduces a role for attr_accessible with :as option,
attr_accessible :name, :is_admin, :as => :admin
My question is, if a user log in, where and how can I assign the user to :admin role so she/he gets the right to mass assign with attr_accessible? Also can I define my own role such as group_to_update? If it does, what should go into the definition of group_to_update?
Thanks.
You are using some technical terminology in vague ways that is making your understanding of this process muddled, so I’m going to clear up this terminology first.
The ‘role’ used in the
:asparameter toattr_accessibleis not a user role. It is an attribute role. It means that attribute is protected from overwriting unless that role is specified in the statement that sets the attribute. So, this system is independent of any user system. Your application doesn’t even need to have users to have roles in mass assignment.Roles are not really “defined” in any formal sense at all. In any place that a role is expected, simply use any symbol/string (e.g.
:group_to_update) as the role. No need to specify it anywhere else ahead of time.Here’s how it works. Normally, during mass assignment of a hash to model attributes, all of the model’s attributes are used as keys to the assigned hash. So if you have a
Barnmodel andbarninstance of it, with three attributeshorse,cat, andrabbit, then this:Is essentially the same as doing:
Now, if you set any
attr_accessibleon the barn model, only the attributes you set there will be updated when you use mass assignment. Example:Then this:
Will only do this:
Because only ‘cat’ and ‘rabbit’ are set to accessible (‘horse’ is not). Now consider setting an attribute role like this:
First, note that the the role can by anything you want as long as it is a symbol/string. In this case, I made the role
:banana. Now, when you set a role on anattr_accessibleattribute, it normally does not got assigned. This:Will now only do this:
But you can assign attributes using a specific role by using the
assign_attributesmethod. So you can do:This will assign all normally-protected params as well as all params protected under the role
:banana:So consider a longer example with more attributes:
Then you can use those roles when assigning attributes. This:
Corresponds to:
And this:
Corresponds to:
Now, if you choose to, you can make user roles (e.g. a “role” column on your User model) correspond to attribute roles on any model. So you could do something like this:
If this
user‘s role happens to bebanana, then (using our last model example) it will set attributes on barn for cat, rabbit, and horse. But this is just one way to use attribute roles. It is entirely up to you if you want to use them a different way.