I have encountered a problem in my application and realized that I could fix it by setting :without_protection => true
when creating a model, e.g.:
Model.new(params[:model], :without_protection => true).
What exactly is rails protecting the models from? Thanks!
It's protection against unintended mass assignment.
The problem with the code you shown is that users can alter the form and change attributes you don't want them to change, like hashed passwords on users or a published status on posts.
You can use attr_protected
and attr_accessible
on models to protect attributes on your models to be overridden. When an attribute is protected than the value from params
will be ignored (a notice will appear in your log).
class Model < ActiveRecord::Base
attr_accessible :one, :two
end
Before Rails 3.1, that was it. There was no way to configure it afterwards. Now, with Rails 3.1, you can assign roles:
class Model < ActiveRecord::Base
attr_accessible :one, :two, :as => :admin
attr_accessible :one, :as => :regular_user
end
And specify it when doing mass updates (new
or update_attributes
):
Model.new(params[:model], :as => :regular_user)
Using :without_protection
, will make every attribute free to be mass assigned and should be used VERY sparingly. Never use when you're passing in user data. You might use it in db/seeds.rb
for example.
This protects you against mass assignment.
Assume that, your model looks something like that:
class CreditCard
belongs_to :user
end
You wouldn't like that someone will call your update action on creditcards_controller and pass another user_id attribute in params[:credit_card]
You can read more about mass assignment security here
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