【发布时间】:2015-09-02 22:55:28
【问题描述】:
在尝试使用 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 page 上的说明进行升级。
我取一个模型,去掉 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的值是多少
问题:这根本行不通。
Foo 类
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 的任一值,要么都成功,要么都失败。出于迭代测试的目的,我想要一种传统批量分配失败而更新代码成功的情况。
我在哪里步履蹒跚?
【问题讨论】:
标签: ruby-on-rails ruby rspec strong-parameters mass-assignment