Rails 3.2.8 中的强参数 [英] Strong Parameters in Rails 3.2.8
问题描述
该视频指出可以保护通过控制器输入的输入,但仍然可以做到通过模型和规格进行质量分配.但是,在 3.2.8 中使用 strong_parameters 时,我没有看到将此记录为一项功能.
This video states that it is possible to protect the input coming in via the controller yet still be able to do mass assignment via models and specs. However, I have not seen this documented as a feature when using strong_parameters in 3.2.8.
我知道我需要将 ActiveModel::ForbiddenAttributesProtection
混合到我的模型中并在 config/application.rb 中设置
config.active_record.whitelist_attributes = false
代码>.我还从模型中提取了所有 attr_accessible
调用.
I understand that I need to mix in ActiveModel::ForbiddenAttributesProtection
into my models and set config.active_record.whitelist_attributes = false
in config/application.rb
. I have also pulled all of my attr_accessible
calls from the model.
无论是否使用 mixin,我都会遇到大量分配错误.
With or without the mixin I am getting mass assignment errors.
ActiveModel::MassAssignmentSecurity::Error:无法批量分配受保护的属性:home_phone、cell_phone
我错过了什么吗?
推荐答案
建议的 RailsCast 可能是一个好的开始,但这里总结了在 Rails 3.x 中你必须做什么才能使强参数而不是 attr_accessible 起作用:
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:
将
gem 'strong_parameters'
添加到您的 Gemfile 并运行 bundle.
Add
gem 'strong_parameters'
to your Gemfile and run bundle.
在 config/application.rb 中注释掉(或设置为 false)config.active_record.whitelist_attributes = true
Comment out (or set to false) config.active_record.whitelist_attributes = true
in config/application.rb
在您的模型中混合ActiveModel::ForbiddenAttributesProtection
.按模型执行此操作,或通过以下方式全局应用于所有模型:
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)
(railscast 建议在新的初始化程序中执行此操作:config/initializers/strong_parameters.rb)
(The railscast proposes to do this in a new initializer: config/initializers/strong_parameters.rb )
从现在开始,您将不得不使用如下语法:
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 )
当您更新模型时.在这种情况下,params[:model]
中除 :attribute
和 :another_attribute
之外的任何属性都将导致 ActiveModel::ForbiddenAttributes 错误.
when you update your models. In this case any attribute in params[:model]
except :attribute
and :another_attribute
will cause an ActiveModel::ForbiddenAttributes error.
您还可以使用 ActionController::Parameters
中的其余新魔法,例如 .require(:attribute)
来强制存在属性.
You can also use the rest of the new magic from ActionController::Parameters
, such as .require(:attribute)
to force the presence of an attribute.
这篇关于Rails 3.2.8 中的强参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!