Reputation: 10862
My model includes an 'admin' field, which is true or false. It is not on 'attr_accessible' because we don't want a bad guy to be able to trick our controller into giving 'admin' privs to a user.
Because, if I am logged in as an admin in my model, I 'do' want to be able to update any user's record to make or take away admin from them. So... the lack of attr_accessible on admin prevents me from doing so.
Maybe that's not the right way to look at it. What's the right way to handle such a case?
Upvotes: 2
Views: 98
Reputation: 107728
Rails 3.2 added a feature that would allow you to do what you're describing. Simply define this in your model:
attr_accessible accessible_attributes + [:admin], :as => :admin
And then in the controller where you want to assign the admin attribute, do this:
User.new(params[:user], :as => :admin)
or
user.update_attributes(params[:user], :as => :admin)
All the attributes that are listed prior to the attr_accessible
call with :as => :admin
will be accessible attributes for any Active Record call that supports the :as => :admin
option.
If you didn't call accessible_attributes
in that definition, then only the attributes defined there will be accessible.
Upvotes: 4