[英]Upgrading to Rails 4 - Strong Parameters
尝试使用strong_parameters gem将项目从3.2逐步升级到Rails 4时,出现了一些不一致的行为。
在config / application.rb中,我有以下内容:
config.active_record.whitelist_attributes = false
config.action_controller.action_on_unpermitted_parameters = :raise
我正在按照gem的github页面上说明的升级过程进行操作。
我采用一个模型,去掉attr_accessible和attr_protected,并在类定义的第一行添加include ActiveModel::ForbiddenAttributesProtection
。 然后,我运行rspec来查找哪些测试是红色的,以尝试将它们变为绿色。
class Bar < ActiveRecord::Base
include ActiveModel::ForbiddenAttributesProtection
...
end
let(:bar) { Bar.create(type: "#{klass_name}") }
和
let(:bar) {
raw_params = { type: "#{klass_name}" }
params = ActionController::Parameters.new(raw_params)
Bar.create(params.permit(:type))
}
都产生
ActiveModel::MassAssignmentSecurity::Error:
Can't mass-assign protected attributes: type
无论config.active_record.whitelist_attributes
的值如何
问题:这根本不起作用。
class Foo < Bar
...
end
对彼此而言
before :each do
Foo.create(status: 'active')
end
和
before :each do
raw_params = { status: 'active' }
params = ActionController::Parameters.new(raw_params)
Foo.create(params.permit(:status))
end
当config.active_record.whitelist_attributes = false
,两个都变为绿色,并正确删除.permit(:status)
Failure/Error: Foo.create(params)
ActiveModel::ForbiddenAttributes:
ActiveModel::ForbiddenAttributes
当config.active_record.whitelist_attributes = true
,两者都产生
Failure/Error: Foo.create(params.permit(:status))
ActiveModel::MassAssignmentSecurity::Error:
Can't mass-assign protected attributes: status
问题:对于whitelist_attributes的任何一个值,要么成功要么都失败。 为了进行迭代测试,我想要一种传统的批量分配失败而更新的代码成功的情况。
我在哪里摇摇欲坠?
首先,如果要升级到Rails 4并使用strong_parameters
gem,则应该具有
config.active_record.whitelist_attributes = false
和
ActiveRecord::Base.send(:include, ActiveModel::ForbiddenAttributesProtection)
其次,似乎'type'是为Rails https://github.com/rails/strong_parameters/issues/142保留的,因此这就是为什么即使您允许该type
键也仍然给出错误的原因。
我的解决方案是在要保存时通过诸如bar.type = 'YourType'
这样的setter方法设置type
。 这将毫无问题。
希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.