Forum: Ruby on Rails More HABTM Save Problems/Issues.. bugs?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
A9a2faf6a73b4924b73532308cf34a8b?d=identicon&s=25 Chris Shorrock (Guest)
on 2005-12-16 08:27
(Received via mailing list)
I seem to be having a problem working with an object which has a
HABTM relationship with another object I know there's been a lot of
talk recently about problems using dual HABTM in a single object but
I believe this may be a separate issue. It appears like I'm unable to
persist this relationship (i.e. the object saves but none of the
entries in the join table are created even though the "arts" object
is populated) during the initial save, yet it I update the exact same
object it properly updates the database. I have an model which looks
like the following:

	class Event < ActiveRecord::Base
		...
		has_and_belongs_to_many :arts
		...
	end

for testing purposes I have a form with some fields that I'm using to
populate this object:
	<input type="hidden" name="event[art_ids][]" value="1">
	<input type="hidden" name="event[art_ids][]" value="2">
	<input type="hidden" name="event[art_ids][]" value="3">

finally my controller, when I attempt to save the object it doesn't
save the 3 join rows in the arts_events table (even though they do
exist in the object), my save method looks like:

	def add
		@event = Event.new( params[:event] )
		@event.user  = @session[:user]

		if @request.post? and @event.save
			redirect_to :action=>:view, :id=>@event.id
		end
	end

the odd thing is, is when I access the EXACT same form but update
this object with the following update method it creates the 3
arts_events

	def edit
		@event = Event.find_by_user_and_id( @session[:user], params[:id] )
		@event.update_attributes( params[:event] )

		if @request.post? and @event.save
			flash.now[:notice] = "event record has been sucessfully updated"
		end
	end

now to further prove my point that it doesn't work with saving, but
it does work with updating I change the add method to the following
which saves all the 3 rows in the arts_events table

	def add
		@event = Event.new( params[:event] )
		@event.user  = @session[:user]

		if @request.post? and @event.save
			@event.reload
			@event.update_attributes( params[:event] )
			@event.save
			redirect_to :action=>:view, :id=>@event.id
		end
	end

Any insight anyone could provide would be appreciated.. Thanks

Chris
This topic is locked and can not be replied to.