2014-09-05 78 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