I have a nested form inside a parent form that allows you to add fields inside the parent form. The idea is that a book can have many schools and the school belongs to the book(habtm) relationship. here are my models:
books.rb
accepts_nested_attributes_for :author
accepts_nested_attributes_for :gallery, :allow_destroy => true
accepts_nested_attributes_for :schools, :reject_if => :find_school, :allow_destroy => true
accepts_nested_attributes_for :images, :allow_destroy => true
def find_school(school)
if existing_school = School.find_by_school_name(school['school_name'])
self.schools << existing_school
return true
else
return false
end
end
school.rb
class School < ActiveRecord::Base
has_and_belongs_to_many :books
validates :school_name, :address, presence: true
#validates_uniqueness_of :school_name
end
In my form for the book I have this setup:
<div id="school" class="field">
<h3>Schools reading this book (add the name and full address of the school)</h3>
<%= f.simple_fields_for :schools, :wrapper => 'inline' do |builder| %>
<%= render 'school_fields', :f => builder %>
<%= link_to_add_association 'add school', f, :schools, :render_options => {:wrapper => 'inline' }, :class => 'fa fa-plus' %>
<% end %>
</div>
In here it should render the fields but I get this
The issue i have is that in my book.rb model the find_school
method keeps returning multiple values of the same books when I update the book. The idea is that the find_school
method basically stops duplicate schools being created as records and just assigns them as a relationship to the book instead. What I am finding is that this self.schools << existing_school
on update just keeps duplicating the fields in the edit form and adds the fields as entries on the item when I check in the params output.
Can anyone help with this