Bra*_*sen 17 ruby-on-rails strong-parameters
该视频表明,可以保护通过控制器输入的输入,但仍然可以通过型号和规格进行质量分配.但是,在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
我错过了什么吗?
Jon*_*son 23
建议的RailsCast可能是一个好的开始,但这里总结了你在Rails 3.x中要做的事情,以获得强大的参数而不是attr_accessible:
添加gem 'strong_parameters'到您的Gemfile并运行bundle.
config.active_record.whitelist_attributes = true在config/application.rb中注释掉(或设置为false)
混合在ActiveModel::ForbiddenAttributesProtection您的模型中.按模型执行此操作,或全局应用于所有模型:
ActiveRecord::Base.send(:include, ActiveModel::ForbiddenAttributesProtection)
(railscast建议在新的初始化程序中执行此操作:config/initializers/strong_parameters.rb)
从现在开始,您将不得不使用如下语法:
model_params = params[:model].permit( :attribute, :another_attribute )
@model.update_attributes( model_params )
Run Code Online (Sandbox Code Playgroud)
当您更新模型时.在这种情况下,params[:model]除了:attribute和:another_attribute将导致ActiveModel :: ForbiddenAttributes错误的任何属性.
您还可以使用其余的新魔法ActionController::Parameters,例如.require(:attribute)强制存在属性.