【问题标题】:Unable to clear Rails ForbiddenAttributesError无法清除 Rails ForbiddenAttributesError
【发布时间】:2015-08-20 09:31:22
【问题描述】:

我已经开始收到ActiveModel::ForbiddenAttributesError,我不知道为什么,也不能轻易清除它:

> Product.new(params[:product])
ActiveModel::ForbiddenAttributesError: ActiveModel::ForbiddenAttributesError
from ~/.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activemodel-4.1.5/lib/active_model/forbidden_attributes_protection.rb:21:in `sanitize_for_mass_assignment'

> h = params[:product]
=> {"title"=>"a", "description"=>"b"}

> Product.new(h)
ActiveModel::ForbiddenAttributesError: ActiveModel::ForbiddenAttributesError

> h.respond_to?(:permitted?)
=> true

> h.permitted?
=> false

> h.permit!
=> {}

> Product.new(h)
ActiveModel::ForbiddenAttributesError: ActiveModel::ForbiddenAttributesError

> h
=> {"title"=>"a", "description"=>"b", "permit"=>{}}

> h.permitted?
=> false

> params[:product].class
=> Hashie::Mash

> h.class
=> Hashie::Mash

所以我发现我需要将其复制到 ActionController::Parameters 对象中:

> s = ActionController::Parameters.new(h)
=> {"title"=>"a", "description"=>"b"}

> s.permitted?
=> false

> s.permit!
=> {"title"=>"a", "description"=>"b"}

> Product.new(s)
=> ok

这是从 API 端点调用的,而不是控制器。

模型非常简单,只是验证和关联。

使用 Rails v4.1.5

【问题讨论】:

  • 略有不同的@axelTetzlaff,因为这是通过控制器进行的,这里我从 API 端点调用 AR。此外,该线程中没有解决我的问题的解决方案,所以我不认为它是重复的。

标签: ruby-on-rails validation


【解决方案1】:

要么做

Product.new(params[:product].permit!)

或创建允许您的属性的新私有方法 -

 def permit_params
   params.require(:product).permit(:title, :description)
end

【讨论】:

  • 您的第一个建议有效。对于第二个,我猜您的建议是将permit_params 放入控制器中?其中必须显式调用!正如我所说,我不是通过控制器而是通过 API。把它放在我的 API 类中会给我params.require(:product) => TypeError: no implicit conversion of Symbol into Stringparams.require("product") => LoadError: cannot load such file -- product
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-05
  • 2014-04-30
  • 1970-01-01
  • 1970-01-01
  • 2013-12-07
相关资源
最近更新 更多