Search code examples
ruby-on-railsnested-formsfields-for

Rails build fields_for once inside fields_for


in my

<%= nested_form_for @object do |f| %>

I've a nested_form like:

<%=f.fields_for :nested, :url => { :action => "new" } do |build| %>
   <%= render 'nested_fields', :f => build %>
<% end %>

and inside that nested_field, I've another fields_for :nested2

My Problem is: I want nested2 appearing 1 time, when nested is called. I tried inside the new action of the nested controller the

@nested = Nested.new
@nested.nested2.build

but this does only work for the "real" new action. Is there any solution for that problem?

I'm using the "nested_form" gem.


Solution

  • fields_for lets you specify a particular object to render the fields for, so if you want your nested_fields partial to contain nested fields for a single, newly build nested2 model, you can do it in the fields_for call itself, like this:

    # '_nested_fields.html.erb'
    
    ...
    <%= f.fields_for :nested2, f.object.build_nested2 do |build| %>
      <%= ... %>
    <% end %>
    

    This is assuming that Nested has_one :nested2, if it's a has_many association the fields_for arguments would be slightly different:

    <%= f.fields_for :nested2s, f.object.nested2s.build do |build| %>
    

    f.object allows you to access the form builder's object, and you can then use it's association methods (based on the association type) to build the new object at that point.