Strong Parameters in Rails 3.2.8

最后都变了- 提交于 2019-11-28 20:35:56
Jonas Schubert Erlandsson

The suggested RailsCast is probably a good start, but here is a summary of what you have to do in Rails 3.x to get strong parameters working instead of attr_accessible:

  1. Add gem 'strong_parameters' to your Gemfile and run bundle.

  2. Comment out (or set to false) config.active_record.whitelist_attributes = true in config/application.rb

  3. Mix in the ActiveModel::ForbiddenAttributesProtection in your model. Do this per model, or apply globally to all models with:

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

    (The railscast proposes to do this in a new initializer: config/initializers/strong_parameters.rb )

  4. From now on you will have to use syntax such as this:

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

    when you update your models. In this case any attribute in params[:model] except :attribute and :another_attribute will cause an ActiveModel::ForbiddenAttributes error.

You can also use the rest of the new magic from ActionController::Parameters, such as .require(:attribute) to force the presence of an attribute.

It isn't the same as your issue but it may come up for someone else getting MassAssignmentSecurity::Error. I've hit an issue that 'id' and 'type' attributes seem to be protected by default even when I had taken the prescribed steps to switch to using strong parameters rather than mass assignment protection. I had an association named 'type' which I renamed to 'project_type' to resolve the problem (the attribute was already project_type_id).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!