Search code examples
ruby-on-railsrubyruby-on-rails-5cocoon-gem

Using cocoon gem to add nested forms. Facilities will not save unless a Toilet is created first


I'm going off by the tutorial that's in the cocoon gem. When trying to create a Toilet the facilities that I'm adding won't save unless the Toilet is created first. I was thinking that it should have been created together as is. Is there a way to save the facilities when creating the toilet?

To not get things confused

class Toilet < ApplicationRecord
 has_many :facilities
  accepts_nested_attributes_for :facilities, reject_if: :all_blank, allow_destroy: true
 end

 class Facility < ApplicationRecord
  belongs_to :toilet
 end

Toilet controller

def new
 @toilet = Toilet.new
end

def create
 @toilet = Toilet.new(toilet_params)
 if @toilet.save
  redirect_to @toilet
 else
  render :new
 end
end

private
 def toilet_params
  params.require(:toilet).permit(:name, :location, facilities_attributes: [:id, :name, :_destroy])
 end

_form.html.erb

<%= f.simple_fields_for :facilities do |facility| %>
 <%= render 'facility_fields', :f => facility %>
<% end %>
<div class='links'>
 <%= link_to_add_association 'add facility', f, :facilities %>
</div>
 <%= f.submit 'Save' %>
<% end %>

_facility_fields.html.erb

<div class='nested-fields'>
 <%= f.inputs do %>
  <%= f.input :name %>
  <%= link_to_remove_association "remove facility", f %>
 <% end %>
</div>

Solution

  • Wesley, yes - you should be able to save both parent & nested at the same time. Long version: Yes, you can create a new record, before saving it, dynamically add some nested content & for the first time for either, save them both at the same time.

    I believe your issue is probably in the _facility_fields.html.erb ... you have a <% f.inputs do %> that looks out of place or is just setup wrong. As you already have a do loop wrapping your render command, you shouldn't need this other do loop. That also means you want to remove the end thing from the template just above the /div.

    _facility_fields.html.erb
    
    <div class='nested-fields'>
     <%= f.inputs do %>             // Issue is this line
      <%= f.input :name %>
      <%= link_to_remove_association "remove facility", f %>
     <% end %>                      // Remove this too afterwards
    </div>