Ruby on rails 无法清除Rails禁止属性错误

Ruby on rails 无法清除Rails禁止属性错误,ruby-on-rails,validation,Ruby On Rails,Validation,我开始感到不安,我不知道为什么,也不容易弄清楚: > 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_pro

我开始感到不安,我不知道为什么,也不容易弄清楚:

> 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

可以

Product.new(params[:product].permit!)
或者创建新的私有方法,允许您的属性-

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

复制稍微不同的@axelTetzlaff,因为这是通过控制器进行的,这里我从API端点调用AR。另外,在这个线程中没有解决我的问题的方法,所以我不认为它是重复的。你的第一个建议是有效的。对于第二个,我猜您的建议是将
permit_params
放在控制器中?它必须被显式地调用!正如我所说的,我不是通过一个控制器而是一个API。将它放在API类中会给我
params.require(:product)=>TypeError:没有将符号隐式转换为字符串
,或者
params.require(“product”)=>LoadError:无法加载这样的文件--product