问题
I was upgrading my project from Rails3 to Rails4 with this tutorial: RailsCasts
I have a model:
class Test < ActiveRecord::Base
validates :content, :presence => true, :length => { :minimum => 2 }
validates :name, :presence => true, :length => { :minimum => 2 }
validates :value, :presence => true
end
After upgrading, in rails console I tried to create new test object
Test.create(name: "asd", content:"asd", value: 5)
And got
WARNING: Can't mass-assign protected attributes for Achievement: name, content, value
(0.2ms) BEGIN
(0.2ms) ROLLBACK
=> #<Test id: nil, name: nil, content: nil, value: nil, created_at: nil, updated_at: nil>
Looks like I forgot to upgrade something. I tried to re-create rails application with overriding config and other rails files, but nothing changed.
I created new empty project and copied model files. It was working OK.
If I'll add
config.active_record.whitelist_attributes = false
to config/application.rb, my upgraded project will be working good. But it's not normal, because in empty rails4, this line was deleted.
What I forgot to upgrade or what must I do, to make upgraded project to work like empty created with rails4 and without config.activerecord ...?
UPD
raw_params = {:name => "asdasd", :content=>"asdasdasd", :value=>5}
=> {:name=>"asdasd", :content=>"asdasdasd", :value=>5}
2.0.0dev :002 > params = ActionController::Parameters.new(raw_params)
=> {"name"=>"asdasd", "content"=>"asdasdasd", "value"=>5}
2.0.0dev :003 > test = Test.create(params.permit(:name, :value, :content))
WARNING: Can't mass-assign protected attributes for Achievement: name, value, content
(0.2ms) BEGIN
(0.2ms) ROLLBACK
=> #<Test id: nil, name: nil, content: nil, value: nil, created_at: nil, updated_at: nil>
回答1:
In Rails 4, attr_accessible is not used any more to do mass-assignment checking. Mass-assignment refers to the practice of creating or updating a Model object by passing a hash of values. When you do mass-assignment in Rails 4, you have to specify which parameters are allowed and which ones are not. This is due to security reasons.
Take a look at the repository for strong_parameters, it contains a brief explanation of how mass-assignment security works in Rails 4. Especially look at Use Outside Of Controllers.
来源:https://stackoverflow.com/questions/17510977/upgrading-rails-3-2-to-rails-4-and-params