简体   繁体   English

即使属性在attr_accessible中,也如何批量分配Rails?

[英]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.

相关问题 Rails 3.1 - 无法批量分配受保护的属性(即使添加到attr_accessible) - Rails 3.1 — Can't mass assign protected attributes (even though added to attr_accessible) “无法批量分配受保护的属性”错误,即使它们存在于attr_accessible中 - “Can't mass-assign protected attributes” error, even they exists in attr_accessible 即使我使用attr_accessible也无法批量分配受保护的属性 - Can't mass-assign protected attributes even if I use attr_accessible 无法批量分配受保护的属性,但可以在attr_accessible中进行分配 - Can't mass-assign protected attributes but assign in attr_accessible 如何修复嵌套字段大量分配受保护属性错误? 尽管有attr_accessible - How do I fix nested fields mass-assign protected attributes error? despite having attr_accessible 即使在attr_accessible中指定,也无法以嵌套形式批量分配属性 - Can't mass-assign attributes in nested form despite specifying in attr_accessible 无法大规模分配受保护的属性:当有attr_accessible时 - having Can't mass-assign protected attributes: when there is attr_accessible 无法批量分配受保护的属性。 (已设置attr_accessible) - Can't mass-assign protected attributes. (attr_accessible is set) 在特殊情况下为attr_accessible:association_attributes进行批量分配 - Mass assign for attr_accessible :association_attributes in special cases Rails - attr_accessible和质量分配 - Rails - attr_accessible & mass assignment
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM