【发布时间】: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。此外,该线程中没有解决我的问题的解决方案,所以我不认为它是重复的。