ruby-on-railsactiveview

Nested forms in Rails with dynamically created objects


I'm looking for a way to create a form for a has_many association so I could be able to set dynamically the amount of objects that would go there.

So far I saw examples when you initialize the association with blank objects, like this:

2.times { @office.employees.build }

So, after you could use fields_for, or whatever, and it works. In situation like mine I don't know exactly how many employees would be added (could be even zero).

Do they have any simple solution on how to end up with a form that will dynamically create a hash like:

{..., "employees" => {"0" => {...}, "1" => {...}}

Thanks in advance.


Solution

  • Take a look at Ryan Bates Railscasts about your topic:

    http://railscasts.com/episodes?utf8=%E2%9C%93&search=nested+model+form

    You will find the perfect solution in these tutorials.

    Ryan explains how you could add a link to dynamically add and remove your needed form fields.