Following the ruby on rails guide developer can't mass-assign protected fields but don't get exception trying to do it, right?
But in my case mass-assignment different params through new
method in rails
application:
@edition = Edition.new params[:edition]
raise following exception:
ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: price
Why? Did I understand something incorrectly? Is it a way not to get the mass-assignment exception? It's not convenient to delete protected attributes from hashes before assignments i think.
Update: Edition model:
class Edition < ActiveRecord::Base
attr_accessible :title, :description
attr_protected :price
end
params[:edition].inspect
:
{"title"=>"t", "description"=>"d", "price"=>"123"}
You are attempting to assign protected attribute price in mass assignment by putting
@edition = Edition.new params[:edition]
That is a mass assignment of variables and in params[:edition] according to your edit, there is the variable price which according to your code cannot be mass assigned.
To fix this you either have to remove the protection on price which I do not think you would want to do or mass-assign only the unprotected variables with new and then assign the protected variable. SO:
@edition = Edition.new params[:edition].except("price")
@edition.price = params[:edition]['price']
OR @edition = Edition.new params[:edition], :without_protection => true
EDIT: news.ycombinator.com/item?id=3780963 Rails 3.23 now makes the validation strict by default which raises that exception. The documentation is out of date.