问题描述
我使用本教程将我的项目从 Rails3 升级到 Rails4:RailsCasts
I was upgrading my project from Rails3 to Rails4 with this tutorial: RailsCasts
我有一个模型:
class Test < ActiveRecord::Base
validates :content, :presence => true, :length => { :minimum => 2 }
validates :name, :presence => true, :length => { :minimum => 2 }
validates :value, :presence => true
end
升级后,在 Rails 控制台中,我尝试创建新的测试对象
After upgrading, in rails console I tried to create new test object
Test.create(name: "asd", content:"asd", value: 5)
得到了
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>
我好像忘记升级东西了.我尝试使用覆盖配置和其他 rails 文件重新创建 rails 应用程序,但没有任何改变.
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.
如果我要补充
config.active_record.whitelist_attributes = false
到 config/application.rb,我升级后的项目将运行良好.但是不正常,因为在空的rails4中,这一行被删除了.
to config/application.rb, my upgraded project will be working good. But it's not normal, because in empty rails4, this line was deleted.
我忘记升级什么或我必须做什么,使升级后的项目像使用 rails4 创建的空一样工作,而没有 config.activerecord ...?
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 ...?
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>
推荐答案
在 Rails 4 中,attr_accessible
不再用于进行批量赋值检查.批量分配是指通过传递值的散列来创建或更新模型对象的做法.在 Rails 4 中进行批量赋值时,必须指定哪些参数是允许的,哪些是不允许的.这是出于安全原因.
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.
查看strong_parameters 的存储库,其中简要说明了批量分配安全性适用于 Rails 4.特别是查看在控制器之外使用.
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.
这篇关于将 Rails 3.2 升级到 Rails 4 和 Params的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!