I currently have a complex form with deep nesting, and I am using the Cocoon gem to dynamically add sections as required (e.g. if a user wants to add another vehicle to the sale form). Code looks like this:
<%= sale.fields_for :sale_vehicles do |sale_vehicles_builder| %>
<%= render :partial => "sale_vehicles/form", :locals => {:f => sale_vehicles_builder, :form_actions_visible => false} %>
<% end -%>
<div class="add-field-links">
<%= link_to_add_association '<i></i> Add Vehicle'.html_safe, sale, :sale_vehicles, :partial => 'sale_vehicles/form', :render_options => {:locals => {:form_actions_visible => 'false', :show_features => true, :fieldset_label => 'Vehicle Details'}}, :class => 'btn' %>
</div>
This works very nicely for the first level of nesting - the sale_vehicle
object is built correctly by Cocoon, and the form renders as expected.
The problem comes when there is another level of nesting - the sale_vehicle
partial looks like this:
<%= f.fields_for :vehicle do |vehicle_builder| %>
<%= render :partial => "vehicles/form", :locals => {:f => vehicle_builder, :f_parent => f, :form_actions_visible => false, :show_features => true, :fieldset_label => 'Vehicle Details'} %>
<% end -%>
The partial for the vehicle
is rendered with no fields, because no sale_vehicle.vehicle
object has been built.
What I need to do is thus build the nested object along with the main object (Cocoon does not currently build any nested objects), but how best to do this? Is there any way to select nested forms from the helper code so that these can be built?
Cocoon currently build the main object like this:
if instance.collection?
f.object.send(association).build
else
f.object.send("build_#{association}")
end
If I could do something like the following, it would keep things nice and simple, but I'm not sure how to get f.children
- is there any way to access nested form builders from the parent form builder?
f.children.each do |child|
child.object.build
end
Any help appreciated to get this working, or suggest another way of building these objects dynamically.
Thanks!
EDIT: Probably worth mentioning that this question appears to be relevant to both the Cocoon gem mentioned above, and also Ryan Bates' nested_form gem. Issue #91 for the Cocoon gem appears to be the same problem as this one, but the workaround suggested by dnagir (delegating the building of the objects) is not ideal in this situation, as that will cause issues on other forms.