17

该视频指出,可以保护通过控制器进入的输入,但仍然可以通过模型和规格进行批量分配。但是,在 3.2.8 中使用 strong_parameters 时,我没有看到此功能被记录为功能。

我知道我需要混合ActiveModel::ForbiddenAttributesProtection到我的模型中并设置config.active_record.whitelist_attributes = false. config/application.rb我还attr_accessible从模型中提取了所有呼叫。

不管有没有 mixin,我都会收到大量分配错误。

ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: home_phone, cell_phone

我错过了什么吗?

4

2 回答 2

23

建议的RailsCast可能是一个好的开始,但这里总结了在 Rails 3.x 中你必须做什么才能让强参数而不是 attr_accessible 工作:

  1. 添加gem 'strong_parameters'到您的 Gemfile 并运行 bundle。

  2. config.active_record.whitelist_attributes = true在 config/application.rb 中注释掉(或设置为 false)

  3. ActiveModel::ForbiddenAttributesProtection在你的模型中混合。每个模型执行此操作,或全局应用于所有模型:

    ActiveRecord::Base.send(:include, ActiveModel::ForbiddenAttributesProtection)

    (railscast 建议在新的初始化程序中执行此操作: config/initializers/strong_parameters.rb )

  4. 从现在开始,您将不得不使用如下语法:

    model_params = params[:model].permit( :attribute, :another_attribute )
    @model.update_attributes( model_params )
    

    当您更新模型时。在这种情况下,params[:model]除了:attribute和中的任何属性:another_attribute都会导致 ActiveModel::ForbiddenAttributes 错误。

您还可以使用来自 的其余新魔法ActionController::Parameters,例如.require(:attribute)强制属性的存在。

于 2013-01-10T07:42:43.850 回答
2

它与您的问题不同,但它可能会出现在其他人获得 MassAssignmentSecurity::Error 的情况下。我遇到了一个问题,即“id”和“type”属性似乎在默认情况下受到保护,即使我已采取规定步骤切换到使用强参数而不是批量分配保护。我有一个名为“type”的关联,我将其重命名为“project_type”以解决问题(该属性已经是 project_type_id)。

于 2013-01-12T12:10:44.840 回答