Search code examples
ruby-on-rails-3simple-formfields-for

Ruby on Rails - simple_form fields_for create different index


I have a question about updating one-to-many fields using simple_form field_for method

I have 2 models, Company and Clients, which has a one-to-many relationship. I displayed clients using field_for, but for UI reason, I had to called it twice. But for some reason, the index of the input fields was given a different value. Below is my code

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

Say if I had 3 clients, the output for the name of the input fields became

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

and

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

This result in duplicating clients during store. How do I solve this?


Solution

  • An easy workaround would be "caching" the form fields like so:

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