[英]Strong_parameters not working
With Ruby 1.9.3, Rails 3.2.13, Strong_parameters 0.2.1: 使用Ruby 1.9.3,Rails 3.2.13,Strong_parameters 0.2.1:
I have followed every indication in tutorials and railscasts, but I can not get strong_parameters working. 我已经按照教程和railscasts中的所有指示进行操作,但是我无法使strong_parameters正常工作。 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
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
Then, if I go to the form and enter "Name: product 1" and "Color: red" no exception is raised; 然后,如果我进入表单并输入“名称:产品1”和“颜色:红色”,则不会引发任何异常; the new product is saved in the database with no color but with the right name. 新产品将以不带颜色但名称正确的方式保存在数据库中。
What am I doing wrong? 我究竟做错了什么?
Solved. 解决了。
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. 在开发和测试环境中,也会记录该错误。
To change the default behaviour, for instance in development enviroment: config/environments/development.rb: 要更改默认行为,例如在开发环境中:config / environments / development.rb:
# Raises an error on unpermitted attributes assignment
config.action_controller.action_on_unpermitted_parameters = :raise # default is :log
To be honest, is very clearly explained in the github repository. 老实说,在github仓库中已经很清楚地解释了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.