In fact, the solution given by Anil Mauria only works for elements that are dynamically added via javascript using the link_to_add provided by the stone. But for me, he would leave new_association for existing elements.
To correctly identify each nested element (even deeply nested), you can use f.index . The advantage is that if the record already exists (that is, if it was in the database), it will simply be replaced by the index that it has in the array. However, using link_to_add will replace f.index identifier automatically generated by nested_form, just like Anil Maurya’s solution.
For deeply nested solutions, instead of just writing fields_for and using the same variable f each time, if you need to label your elements correctly, you must specify which partial to render, and each time use a different f variable that you must convey partial
For example: if you have
Main has_many :nested1s Nested1 has_many :nested2s Nested2 has_many :nested3s
Then your code should look like this (I gave an example with tables, because it is more complicated):
<%= nested_form_for @Main do |main_form| %> <table> <thead> <stuff /> </thead> <%= main_form.fields_for :nested1s, :wrapper => false do |nested1_f| %> <%= render 'main/nested1_fields', nested1_f: nested1_f %> <% end %>
_nested1_fields.html.erb
<tbody class="fields"> <tr>Stuff</tr> <tr> <table id="nested1-<%= nested1_f.index %>-nested2s"> <thead>Stuff</thead> <%= nested1_f.fields_for :nested2s, :wrapper => false do |nested2_f| %> <%= render 'main/nested2_fields', nested1_f: nested1_f, nested2_f: nested2_f %> <% end %> </table> </tr> <tr><%= nested1_f.link_to_add 'add nested2', :nested2, :data => { :target => "#nested1-#{nested1_f.index}-nested2s"}, class: "btn btn-sm btn-success" %> </tbody>
_nested2_fields.html.erb
<tbody class="fields"> ... <table id="nested1-<%= nested1_f.index %>-nested2-<%= nested2_f.index %>-nested3s"> <%= fields_for :nested3s do |nested3_f| %> ... ... </tbody>
It is also important to note that gem nested_form will only work well if each nested set of fields is wrapped with a tag with a "field" class