【问题标题】:Strong_parameters not working强参数不起作用
【发布时间】:2013-05-14 11:13:47
【问题描述】:

使用 Ruby 1.9.3、Rails 3.2.13、Strong_parameters 0.2.1:

我已遵循教程和 railscasts 中的所有指示,但我无法让 strong_parameters 正常工作。这应该是非常简单的事情,但我看不出错误在哪里。

config/initializers/strong_parameters.rb:

ActiveRecord::Base.send(:include, ActiveModel::ForbiddenAttributesProtection)

config/application.rb

config.active_record.whitelist_attributes = false

app/models/product.rb

class Product < ActiveRecord::Base
end

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 异常。但是当我搬到:

 ...
  def create
    @product = Product.new(product_params)
    # and same flow than before
  end
  private
  def product_params
    params.require(:product).permit(:name)
  end

然后,如果我进入表格并输入“名称:产品 1”和“颜色:红色”,则不会引发异常;新产品保存在数据库中,没有颜色,但名称正确。

我做错了什么?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 strong-parameters


    【解决方案1】:

    解决了。

    默认情况下,使用不允许的属性会静默失败,因此提交的属性会被过滤掉并忽略。在开发和测试环境中,也会记录错误。

    更改默认行为,例如在开发环境中: 配置/环境/development.rb:

    # Raises an error on unpermitted attributes assignment
      config.action_controller.action_on_unpermitted_parameters = :raise  # default is :log
    

    说实话,github仓库里解释的很清楚了。

    【讨论】:

    • 有像this one 这样的教程依赖默认为:raise,这令人困惑。感谢您解决这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-19
    • 2012-11-18
    • 2019-07-06
    • 1970-01-01
    相关资源
    最近更新 更多