[英]How to mass-assign in rails even though attributes are in attr_accessible?
In my like.rb I have: 在我的like.rb中,我有:
class Like < ActiveRecord::Base
attr_accessible :liked, :product_id, :user_id
end
In my controller I have: 在我的控制器中,我有:
@like = Product.new(:product_id => params[:id].to_i, :user_id => current_user.id, :liked => "Yes")
@like.save
However I get an error saying Can't mass-assign protected attributes: product_id, user_id, liked. 但是,我收到一条错误消息,提示无法批量分配受保护的属性:product_id,user_id,喜欢。 Any advice on how to fix this?
有关如何解决此问题的任何建议?
You appear to have set the attributes as accessible on the Like
model, but you're trying to mass-assign on the Product
model. 您似乎已将属性设置为在
Like
模型上可访问,但是您正在尝试在Product
模型上进行批量分配。 If you set attr_accessible
there, you should find things work better. 如果在
attr_accessible
设置attr_accessible
,则应该会发现效果更好。
@Chowlett's answer is correct. @Chowlett的答案是正确的。 If you have fixed set of attributes to assign (like in your example), you can use
without_protection
flag: 如果您要分配固定的属性集(例如您的示例),则可以使用
without_protection
标志:
@like = Product.new({product_id: params[:id].to_i, user_id: current_user.id, liked: 'Yes'}, without_protection: true)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.