[Rails] Re: HABTM and getting to arrays from either direction

Josh Susser josh at hasmanythrough.com
Tue Aug 8 22:23:36 GMT 2006


DWFrank wrote:
> I didn't find exactly an answer on this one, so I'd like to get a 
> clarification from folks who live & breathe HABTM.
> 
> class foo
>   has_and_belongs_to_many :bars
> end
> 
> class bar
>   has_and_belongs_to_many :foos
> end
> 
> (and yes, I have a bars_foos table in my db)
> 
> def test_habtm
>   bar = Bar.new
>   foo = Foo.new
> 
>   foo.bars<<bar
>   assert !foo.bars.empty?
>   assert !bar.foos.empty?
> end
> 
> My first assert passes just fine.  But the 2nd fails.  Am I wrong on the 
> concepts of HABTM? Shouldn't the << operator add to the join table and 
> therefore the next find from either object return a non-empty array?

<< acts different depending on whether the record has been saved or not. 
If it is not a new record (has already been saved), the join table will 
be updated when << is sent. If it hasn't yet been saved, it has no id to 
put in the join table, so it just saves the associated object in the 
bars collection and waits to create the entry in the join table when it 
gets saved. Try saving the objects and see what happens then.

--
Josh Susser
http://blog.hasmanythrough.com/

-- 
Posted via http://www.ruby-forum.com/.


More information about the Rails mailing list