【问题标题】:Rails Nested Form - Can't mass-assign protected attributes:Rails 嵌套表单 - 无法批量分配受保护的属性:
【发布时间】:2012-08-01 08:17:42
【问题描述】:

我使用了nested_form gem,每当我尝试向我的表单提交内容时,我都会收到Can't mass-assign protected attributes:items 消息,即使我已经在我的模型中输入了attr_accessible

表格:

<%= nested_form_for(@goods_in) do |f| %>
...

<%= f.fields_for :items do |i| %>
<td><%= i.text_field :description, :autocomplete => :off%></td>
<td><%= i.text_field :quantity, :autocomplete => :off %></td>
<th><%= i.link_to_remove "Remove this item" %></th>
<% end %>
<%= f.submit :"Submit Delivery" %>
<% end %>

Goods In Model:class GoodsIn

attr_accessible :c4lpono, 
              :courier, 
              :deliverydate,  
              :deliverynoteno,  
              :destination,  
              :notes,  
              :quantity,  
              :signedby,
              :supplier_id,
              :partcode_ids

accepts_nested_attributes_for :supplier

validates :c4lpono, 
              :deliverydate,  
              :deliverynoteno,  
              :destination,  
              :quantity,  
              :signedby,
              :presence =>true                  

end

物品模型

class Item < ActiveRecord::Base
belongs_to :goods_in

attr_accessible :quantity,
              :partcode,
              :description,
              :goods_in_id


accepts_nested_attributes_for :goods_in


end

控制器中的货物:

def create
@goods_in = GoodsIn.new(params[:goods_in])
end

【问题讨论】:

  • 您能否在调用 new、create 或 update_attributes 时显示相关的控制器代码?
  • 添加到我的问题中!

标签: ruby-on-rails nested-forms mass-assignment


【解决方案1】:

你必须添加

attr_accessible :items_attributes

这里是a link 文档:)

【讨论】:

  • 你能告诉我正在发送的日志中的参数吗?
  • {"utf8"=>"✓", "authenticity_token"=>"GBf/8dANkgi9fCWfwluL3drfpksHMReBK1zJveswulE=", "goods_in"=>{"deliverydate"=>"", "deliverynoteno"=>" ", "destination"=>"", "c4lpono"=>"", "courier"=>"", "notes"=>"", "signedby"=>"Carla Dessi", "items"=>{ "partcode"=>"", "description"=>"", "quantity"=>"", "_destroy"=>""}}, "suppliers"=>{"suppliername"=>""}, " commit"=>"提交交付", "collection"=>{"view"=>:get}}
  • 您的关联和模型名称有问题。它应该是has_many :items 和 belongs_to :good_in。你能把这两个模型的完整代码发过来吗?那我可以帮忙:)
  • 将其添加到我的问题中 :)
【解决方案2】:

我认为您的商品模型存在错误。

它应该是has_many :items 而不是has_many :item

【讨论】:

  • 我改变了它并得到了这个:No association found for name item'. Has it been defined yet?
  • 如果您更改了accepts_nested_attributes_for :items 而不是:item
  • 如果我将它们都更改为项目而不是项目,页面加载但字段不显示,如果我只是更改接受嵌套属性部分,我会得到:No association found for name items'. Has it been defined yet?
  • 另外,在你的物品模型中,它应该是belongs_to :goods_in
  • 然后我得到No association found for name 'goods_ins'. Has it been defined yet?
【解决方案3】:

很难说你想用你的模型实现什么,但我认为你想要以下:

您的 GoodsIn 需要具有 accept_nested_attributes_for :items 的关系。 belongs_to 和accepts_nested_attributes_for 已关闭。

【讨论】:

    猜你喜欢
    • 2012-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-05
    • 1970-01-01
    • 2011-06-29
    相关资源
    最近更新 更多