duplicate rows in join table with has_many => through and accepts_nested_attributes_for
Posted
by shalako
on Stack Overflow
See other posts from Stack Overflow
or by shalako
Published on 2010-06-16T02:50:41Z
Indexed on
2010/06/16
2:52 UTC
Read the original article
Hit count: 274
ruby-on-rails
An event has many artists, and an artist has many events. The join of an artist and an event is called a performance. I want to add artists to an event.
This works except that I'm getting duplicate entries into my join table when creating a new event. This causes problems elsewhere.
event.rb
has_many :performances, :dependent => :destroy
has_many :artists, :through => :performances
accepts_nested_attributes_for :artists, :reject_if => proc {|a| a['name'].blank?}
accepts_nested_attributes_for :performances, :reject_if => proc { |a| a['artist_id'].blank? }, :allow_destroy => true
artist.rb
has_many :performances, :dependent => :destroy
has_many :artists, :through => :performances
performance.rb
belongs_to :artist
belongs_to :event
events_controller.rb
def new
@event = Event.new
@event.artists.build
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @event }
end
end
def create
@event = Event.new(params[:event])
respond_to do |format|
if @event.save
flash[:notice] = 'Event was successfully created.'
format.html { redirect_to(admin_events_url) }
format.xml { render :xml => @event, :status => :created, :location => @event }
else
format.html { render :action => "new" }
format.xml { render :xml => @event.errors, :status => :unprocessable_entity }
end
end
end
output
Performance Create (0.2ms) INSERT INTO `performances` (`event_id`, `artist_id`) VALUES(7, 19)
Performance Create (0.1ms) INSERT INTO `performances` (`event_id`, `artist_id`) VALUES(7, 19)
© Stack Overflow or respective owner