2014-09-05 81 views
0

我有關於使用simple_form field_for方法Ruby on Rails的 - simple_form fields_for創建不同的索引

更新one-to-many fields問題我有2種模式,CompanyClients,其中有一個one-to-many關係。 我使用field_for顯示客戶端,但出於UI原因,我不得不調用它兩次。 但由於某些原因,輸入字段的索引被賦予不同的值。下面是我的代碼

<%= simple_form_for @company do |f| %> 
<table> 
    <tr> 
    <td> 
    <%= f.input :name, label: 'Company name: ' %>    
    <%= f.simple_fields_for :clients do |client| %> 
     <%= client.input :name, label: 'Client names: ' %>    
    <% end %> 
    <%= f.input :info, label: 'Company info: ' %>    
    </td> 
    <td class="span2 clients_desc"> 
    <%= f.simple_fields_for :clients do |client| %>   
     <%= client.input :description, label: 'Client description: ' %>   
    <% end %> 
    </td> 
    </tr> 
</table> 
<% end %> 

說,如果我有3個客戶端,輸出爲input fields的名字成爲

company[client_attributes][0][name]company[client_attributes][1][name]company[client_attributes][2][name]

company[client_attributes][3][description]company[client_attributes][4][description]company[client_attributes][5][description]

這導致在存儲過程中複製客戶端。我該如何解決這個問題?

+0

你爲什麼叫它** **兩次?爲什麼不把它們包裝成一個** single **'simple_fields_for'? – Pavan 2014-09-05 04:58:54

+0

這是因爲UI原因,我還不得不在該表中顯示一些其他信息 – hook38 2014-09-05 05:02:40

+0

這是什麼** UI **原因?你能多解釋一下嗎? – Pavan 2014-09-05 05:03:17

回答

2

一個簡單的解決辦法是「緩存」的表單字段像這樣:

# ... 
<%= f.simple_fields_for :clients do |client| %> 
    <%= client.input :name, label: 'Client names: ' %> 
    <% client_description_input = client.input :description, label: 'Client description: ' %>   
<% end %> 
# ... 
<%= client_description_input %> 
# ... 
+0

這樣一個簡單的解決方案,謝謝 – hook38 2014-09-08 01:25:26