Rails中的强参数3.2.8

该video表明可以保护通过控制器输入的输入,但仍然可以通过型号和规格进行质量分配。 但是,在3.2.8中使用strong_parameters时,我没有将此文档记录为function。

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

无论有没有mixin,我都会遇到质量分配错误。

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

我错过了什么吗?

建议的RailsCast可能是一个好的开始,但这里总结了你在Rails 3.x中要做的事情,以获得强大的参数而不是attr_accessible:

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

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

  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)来强制存在属性。

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