强参数不起作用 [英] Strong_parameters not working
问题描述
使用 Ruby 1.9.3、Rails 3.2.13、Strong_parameters 0.2.1:
我遵循了教程和 railscasts 中的所有指示,但我无法让 strong_parameters 工作.应该很简单,但我看不出错误在哪里.
I have followed every indication in tutorials and railscasts, but I can not get strong_parameters working. It should be something really simple, but I can not see where is the error.
config/initializers/strong_parameters.rb:
config/initializers/strong_parameters.rb:
ActiveRecord::Base.send(:include, ActiveModel::ForbiddenAttributesProtection)
config/application.rb
config/application.rb
config.active_record.whitelist_attributes = false
app/models/product.rb
app/models/product.rb
class Product < ActiveRecord::Base
end
app/controllers/products_controller.rb:
app/controllers/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 Attributes 异常.但是当我搬到:
This raises the Forbidden Attributes exception, as expected. But when I move to:
...
def create
@product = Product.new(product_params)
# and same flow than before
end
private
def product_params
params.require(:product).permit(:name)
end
然后,如果我转到表单并输入名称:产品 1"和颜色:红色",则不会引发异常;新产品保存在数据库中,没有颜色但名称正确.
Then, if I go to the form and enter "Name: product 1" and "Color: red" no exception is raised; the new product is saved in the database with no color but with the right name.
我做错了什么?
推荐答案
已解决.
默认情况下,使用不允许的属性会以静默方式失败,因此提交的属性会被过滤掉并忽略.在开发和测试环境中,错误也会被记录下来.
By default, the use of not allowed attributes fails silently and the so submitted attributes are filtered out and ignored. In development and test environments the error is logged as well.
要更改默认行为,例如在开发环境中:配置/环境/development.rb:
To change the default behaviour, for instance in development enviroment: config/environments/development.rb:
# Raises an error on unpermitted attributes assignment
config.action_controller.action_on_unpermitted_parameters = :raise # default is :log
老实说,github仓库里已经解释的很清楚了.
To be honest, is very clearly explained in the github repository.
这篇关于强参数不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!