After reading about attr_accessible in the Rails 3.1 API, I see that there is an as :admin
option in there. I would like to know two things.
If the user has an admin flag, how do does my controller tell my model that the user is an admin.
If the user is an owner, can i specify :as => owner
in my model, and once again how does my controller inform my model they are the owner of an item.
There is no built-in integration with models; you pass in the role in the assign_attributes
call:
@project.assign_attributes(params[:project], :as => :admin)
The :as
parameter defaults to :default
, and you can pass in any symbol that you want. To integrate this into your User
model, you could give it an attribute called role
, and then do something like:
@project.assign_attributes(params[:project], :as => current_user.role.to_sym)
You can also bypass the protection using :without_protection
:
@project.assign_attributes(params[:project], :without_protection => true)
In a similar way, new
, create
, create!
, update_attributes
, and update_attributes!
methods all respect mass-assignment security. The Ruby on Rails guide on security has more info.
For both scenarios, you'd pass it in the same way that you declare it originally. So for example:
class User < ActiveRecord::Base
attr_accessible :name
attr_accessible :credit_card, :as => :admin
end
If you did
user = User.new(:name => "John", :credit_card => "1234123412341234")
Then you won't be able to assign the credit_card
:
user.attributes # {:name => "John", :credit_card => nil}
However, if you state that it will be :as => :admin
then it allows it
user = User.new({:name => "John", :credit_card => "1234123412341234"}, :as => :admin)
user.attributes # {:name => "John", :credit_card => "1234123412341234"}
More information:
http://www.enlightsolutions.com/articles/whats-new-in-edge-scoped-mass-assignment-in-rails-3-1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With