3

Is there a way to dynamically add X number of nested form fields? For example if we have a select menu:

Select Menu -1 -2 -3 -4

And the user selects 3, then create 3 nested form fields.

I have watched the Railscast on Nested model form but to me this already has the one set of fields_for already created and simply inserts them each time the link is clicked. I would like to dynamically insert X amount each time the select menu changes.

Here is some code from the Railscast:

def link_to_add_fields(name, f, association)
  new_object = f.object.send(association).klass.new
  id = new_object.object_id
  fields = f.fields_for(association, new_object, child_index: id) do |builder|
    render(association.to_s.singularize + "_fields", f: builder)
  end
  link_to(name, '#', class: "add_fields", data: {id: id, fields:  fields.gsub("\n", "")})
end
2
  • do you have answer for this? Commented Apr 5, 2018 at 9:00
  • @do_Ob no, I didn't figure it out and moved on. Have you tried cocoon suggested in the answer below? Apparently version 1.2.2 added the ability to add multiple items in one click Commented Apr 5, 2018 at 23:32

1 Answer 1

2

sorry for the late answer, but I was just looking around for the same thing. Had you checked this gem? https://github.com/nathanvda/cocoon

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.