Strong_parameters无效
使用Ruby 1.9.3,Rails 3.2.13,Strong_parameters 0.2.1:
我已经遵循了教程和railscast中的所有指示,但我无法使strong_parameters正常工作。 它应该是非常简单的东西,但我看不出错误在哪里。
配置/初始化/ strong_parameters.rb:
ActiveRecord::Base.send(:include, ActiveModel::ForbiddenAttributesProtection)
配置/ application.rb中
config.active_record.whitelist_attributes = false
应用程序/模型/ product.rb
class Product < ActiveRecord::Base end
应用程序/控制器/ products_controller.rb:
class ExpedientesController < ApplicationController ... def create @product = Product.new(params[:product]) if @product.save redirect_to @product else render :new end end end
这会像预期的那样引发Forbidden Attributesexception。 但是当我搬到:
... def create @product = Product.new(product_params) # and same flow than before end private def product_params params.require(:product).permit(:name) end
然后,如果我转到表单并输入“名称:产品1”和“颜色:红色”,则不会引发exception; 新产品保存在数据库中,没有颜色,但名称正确。
我究竟做错了什么?
解决了。
默认情况下,使用不允许的属性会无提示失败,因此会过滤掉并忽略所提交的属性。 在开发和测试环境中,也会记录错误。
要更改默认行为,例如在开发环境中:config / environments / development.rb:
# Raises an error on unpermitted attributes assignment config.action_controller.action_on_unpermitted_parameters = :raise # default is :log
说实话,在github存储库中非常清楚地解释了。