UPDATED: I am trying to add/remove form fields to a nested form involving multiple models. I have seen the "Dynamic Forms" railscast by Ryan Bates and I have referred to this article using the Cocoon Gem. Following that article has made everything work perfectly except for the child_index. The child_index is present only on the first :kid
input field (:name
) and the first :pet
input fields (:name
and :age
). Then it goes back to an authenticity token for the fields being added.
I've removed all of the JS and helper methods and instead I'm using some of the Cocoon methods that has built in JS.
I fixed the problem where clicking "Add" would add two fields instead of one by removing the = javascript_include_tag :cocoon
from the application.html.erb
file.
I have tried adding jQuery and form helpers but I'm not sure I entered the code correctly.
(I have changed the model objects to make the relationships more clear)
parent.rb file:
class Parent < ActiveRecord::Base
has_many :kids
has_many :pets, through: :kids # <<<<<< ADDED KIDS USING 'through:'
kid.rb file:
class Kid < ActiveRecord::Base
belongs_to :parent
has_many :pets
accepts_nested_attributes_for :pets, reject_if: :all_blank, allow_destroy: true
validates :name, presence: true
pet.rb file:
class Pet < ActiveRecord::Base
belongs_to :kid
validates :name, presence: true
validates :age, presence: true
This is my _form.html.erb file:
<%= form_for @parent do |f| %>
<% if @parent.errors.any? %>
<div class="alert alert-danger">
<h3><%= pluralize(@student.errors.count, 'Error') %>: </h3>
<ul>
<% @student.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="inline">
<div>
<%= f.fields_for :kids do |kid| %>
<%= render 'kid_fields', f: kid %>
<% end %>
<div>
<%= link_to_add_association "Add Kid", f, :kids, id: 'add_kid',
'data-association-insertion-method' => 'before',
'data-association-insertion-traversal' => 'closest' %>
</div>
<% end %>
</div>
</div>
<div class="form-actions">
<%= f.submit 'Create Parent', class: 'btn btn-primary' %>
</div>
<% end %>
This is my _kid_fields.rb file:
<div class="nested-fields">
<div class="kid-fields inline">
<%= f.hidden_field :_destroy, class: 'removable' %>
<%= f.text_field :name, class: 'form-control', placeholder: 'Kid's Name', id: 'kid-input' %>
<div>
<%= link_to_remove_association 'Remove Kid', f %>
</div>
<%= f.fields_for :pets do |pet| %>
<%= render 'pet_fields', f: pet %>
<% end %>
</div>
<div>
<%= link_to_add_association "Add Pet", f, :pets, id: 'add_pet',
'data-association-insertion-method' => 'before' %>
</div>
</div>
This is my _pet_fields.rb file:
<div class="nested-fields">
<div class="pet-fields">
<%= f.hidden_field :_destroy, class: 'removable' %>
<%= f.text_field :name, placeholder: 'Pet Name', id: 'pet-name-input' %>
<%= f.text_field :age, placeholder: 'Pet Age', id: 'pet-age-input' %>
<%= link_to_remove_association 'Remove Pet', f, id: 'remove_pet' %>
</div>
</div>