【问题标题】:Upgrading to Rails 4 - Strong Parameters升级到 Rails 4 - 强参数
【发布时间】: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


    【解决方案1】:

    首先,如果你要升级到 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。这将毫无问题。

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-07
      • 1970-01-01
      相关资源
      最近更新 更多