2012-06-24 41 views
0

所以我有一个实体形式接受另一个实体的嵌套属性。这呈现完美。但是,嵌套窗体不能正常工作,因为我喜欢它。请看下图:接受嵌套属性不按预期工作

<table class="datagrid"> 
    <thead class="datagrid"> 
     <th width="300" align="left">&nbsp;Item</th> 
     <% unless current_user.is_partner? %> 
      <th width="100">&nbsp;Location</th> 
     <% end %> 
     <th>&nbsp;Amount Requested</th> 
     <th>&nbsp;Amount Checked Out</th> 
    </thead> 

    <% session[:clicked_request].items.each do |item| %> 
     <tr class="<%= cycle('dg_list_line_odd', 'dg_list_line_even') %>"> 
     <td>&nbsp;<%= link_to "#{item.name}", item_path(item) %></td> 
      <% unless current_user.is_partner? %> 
      <td>&nbsp;&nbsp;<%= item.location.name %></td> 
      <% end %> 
      <td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<%= item.requested %></td> 
      <td><%= f.text_field :amount, :value => item.requested, :size => 1 %></td> 
     </tr> 
    <% end %> 
</table> 
<p>&nbsp;</p> 

正如你可以看到有一个“每个”循环这里,允许显示,并希望创立,多个项目。然而,当我按下提交按钮时,不管有多少项目,只有其中一个被创建。

您的建议非常感谢。

回答

0

那不是你如何呈现形式与accepts_nested_attributes

假设f是绑定到父对象一个表单生成器,你需要做的是这样

<%= f.fields_for :items do |item_form| %> 
    <%= item_form.text_field :amount 
<% end %> 

该块将每个项目执行一次在集合中。另外,item_form设置了正确的前缀,以使控制器端正常工作。

+0

你几乎正确地期待'accept_nested_attributes'使用'_attributes'来查看writer属性,所以上面的表单必须构建一个hash,它有一个名为'items_attributes'的键,它需要为上面的表单设置'name'明确因为我猜在上面的情况下,它创建了'items'的散列。你可以在'http:// api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html'中检查相同的结果 – Viren

+0

如果你做得对,fields_for会为你设置名字 –

+0

糟糕,我写过form_for而不是字段 –