0

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.

Misha Slyusarev
  • 1,353
  • 2
  • 18
  • 45

2 Answers2

1

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.

Matthias
  • 4,355
  • 2
  • 25
  • 34
0

Please setup the nessted_form gem use this link

= simple_nested_form_for  @ffice do |f|
  = f.fields_for :employees do |employee|    
       = render 'employee_fields', :f => employee
  .links
    = image_tag('plus.png', :class => 'plus-link')      
    = f.link_to_add 'Add another employee', :employees

"link_to_add" this helper method is defined in nessted_form, helps in adding many employee form.

I hope this will helps.

Kiran Kumara
  • 164
  • 5