Rails fields_for :child_index option explanation
Posted
by Timothy
on Stack Overflow
See other posts from Stack Overflow
or by Timothy
Published on 2010-05-21T02:20:51Z
Indexed on
2010/05/21
2:30 UTC
Read the original article
Hit count: 447
ruby-on-rails
I have been trying to create a complex form with many nested models, and make it dynamic. Now I found that making a nested model isn't difficult with accepts_nested_attributes_for, but making it nested and dynamic was seemingly impossible if there were multiple nested models.
I came across http://github.com/ryanb/complex-form-examples/blob/master/app/helpers/application_helper.rb which does it very elegantly. Could anyone shed some light on lines 13 and 16?
13 form_builder.object.class.reflect_on_association(method).klass.new
and
16 form_builder.fields_for(method, options[:object], :child_index => "new_#{method}") do |f|
From intuition, line 13 instantiates a new object, but why must it do so many method calls? I couldn't find any documentation for the :child_index option on line 16. When the form is created, a very large number is used as an index for new models, whereas existing models are indexed by their id. How does this work?
© Stack Overflow or respective owner