【问题标题】:Ruby on Rails - simple_form fields_for create different indexRuby on Rails - simple_form fields_for 创建不同的索引
【发布时间】:2014-09-05 04:56:06
【问题描述】:

我有一个关于使用simple_form field_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]

这会导致在存储期间复制客户端。我该如何解决?

【问题讨论】:

  • 你为什么叫它两次?为什么不将它们包装成一个单个 simple_fields_for
  • 出于 UI 原因,我必须在该表中显示一些其他信息
  • UI 的原因是什么?请您再解释一下。
  • 我放在这里的代码不是我的代码的精确复制,UI 需要一个表,其中有 1 列包含一些公司信息以及所有客户的名称。而另一列包含来自所有客户的一些其他信息。我知道这是一个奇怪的设计,但不是我设计的。
  • 我已经更新了我的代码,让它更有意义

标签: ruby-on-rails-3 simple-form fields-for


【解决方案1】:

一个简单的解决方法是像这样“缓存”表单字段:

# ...
<%= 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 %>
# ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-27
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多