cocoon gem double nested form not working

237 Views Asked by At

_form.html.erb

<%= form_for @business, remote: true, :html => { :id => "newbusinessForm" } do |f|%>
  ...
  <%= f.fields_for LifePage.new do |life_page| %>
    <% life_page.object.spotlights.build %>
      <%= life_page.fields_for :spotlights do |spotlight| %>
        <%= render 'spotlight_fields', spotlight: spotlight %>
      <% end %>
      <div class="links">
        <%= link_to_add_association "Add Spotlight", life_page, :spotlights %>
      </div>
    <% end %>
<% end %>

_spotlight_fields.html.erb

<div class="nested-fields">
  <div class="field">
    <%= spotlight.label :title %>
    <%= spotlight.text_field :title %>  
    <%= link_to_remove_association "Delete", spotlight %>
  </div>
</div>

ERROR: undefined local variable or method `spotlight' for #<#Class:0x00007fc75416cc18:0x00007fc75413eed0>

If added debugger in _spotlight_fields.html.erb file

1st time: spotlight.object returns
 #<Spotlight:0x00007fac85218098 id: nil, title: nil, description: nil, life_page_id: nil, visible: nil, optional_caption: nil, created_at: nil, updated_at: nil>

2nd time: spotlight.object returns nil

I think the nested object is not being initiated correctly.

If I add condition inside _spotlight_fields.html.erb as

<div class="nested-fields">
  <% if local_assigns[:spotlight] %>
    <div class="field">
      <%= spotlight.label :title %>
      <%= spotlight.text_field :title %>    
      <%= link_to_remove_association "Delete", spotlight %>
    </div>
  </div>
<% end %>

and when click on 'add more' button, it generates blank .nested_fields div

0

There are 0 best solutions below