Nested Form: link_to_add: customizing to work with multiple fields_for builders

jquery, nested-forms, ruby-on-rails, ruby-on-rails-3

Solution

I neglected to post the solution I found for this problem. Belatedly, here it is.

I ended up using Single Table Inheritance (STI) for my child types, making each one a class, even though that was overkill for me. Then, the following worked:

<h>ClassOneChild form</h>
<%= f.fields_for :class_one_children do |builder| %>
  ...
<% end %>
<%= f.link_to_add( "add child", :class_one_children ) %>

<h>ClassTwoChild form</h>
<%= f.fields_for :class_two_children do |builder| %>
  ...
<% end %>
<%= f.link_to_add( "add child", :class_two_children ) %>

...

<%= f.submit "Save Children" %>

Problem

I have a nested form with a nested child object type which is repeated on the form so that I can apply various different defaults in the form elements. It doesn't make sense for me to separate them into different classes of child objects because I am only separating them for the purposes of organizing them in a way that makes sense to the user and for populating different defaults; they are otherwise identical. In my partial, I have something like this: ``` Children 1 <%= f.fields_for :children do |builder| %> <% next if not builder.object.type == 1 %> ... fields for type 1 children ... <% end %> <%= f.link_to_add( "add child", :children ) %> Children 2 <%= f.fields_for :children do |builder| %> <% next if not builder.object.type == 2 %> ... fields for type 2 children ... <% end %> <%= f.link_to_add( "add child", :children ) %> ... etc ... ``` This works fine, except that the `link_to_add` always gives fields having the defaults of the final `fields_for/builder` block (i.e. Type N Children), rather than using the defaults for the `fields_for/builder` block immediately above them. How can I give `link_to_add` the right functionality? From https://github.com/ryanb/nested_form#enhanced-jquery-javascript-template : You can override default behavior of inserting new subforms into your form. For example: ``` window.nestedFormEvents.insertFields = function(content, assoc, link) { return $(link).closest('form').find(assoc + '_fields').append($(content)); } ``` It seems to me that there must be some small adjustment to this insertFields function that would have it duplicating the desired form elements, instead of just the final ones on the page. I have only the barest experience with javascript, so I'm hoping someone can please point out what that is! FYI, the full jquery file is here: https://github.com/ryanb/nested_form/blob/master/vendor/assets/javascripts/jquery_nested_form.js Many thanks, Scott

Original source