Nested form: link_to_add: setup for working with multiple fields for builders

I have a nested form with a nested type of a child object that repeats on the form so that I can apply various different default values ​​in the form elements. It makes no sense for me to separate them into different classes of child objects, because I only separate them for their organization in a way that makes sense to the user and for filling in different default values; 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 link_to_add always gives fields with default values ​​for the last fields_for/builder block (i.e. type N of children), instead of using default values ​​for the fields_for/builder block located directly above them. How can I give link_to_add correct functionality?

From https://github.com/ryanb/nested_form#enhanced-jquery-javascript-template :

You can override the default behavior of inserting new subforms into your form. For instance:

  window.nestedFormEvents.insertFields = function(content, assoc, link) { return $(link).closest('form').find(assoc + '_fields').append($(content)); } 

It seems to me that there should be a slight adjustment to this insertFields function, which would duplicate the necessary form elements, and not just the last ones on the page. I have only the most vivid experience with javascript, so I hope someone can please what it is!

FYI, the full jquery file is here: https://github.com/ryanb/nested_form/blob/master/vendor/assets/javascripts/jquery_nested_form.js

Thank you very much Scott

+4
source share
1 answer

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

In the end, I used Single-Inheritance (STI) for my child types, making each of them a class, although that was redundant for me. Then it 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" %> 
+1
source

Source: https://habr.com/ru/post/1413825/


All Articles