2012-06-24 43 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而不是字段 –