Forum: Ruby on Rails HABTM - how to insert join row when associated rows exist

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.
Lindsay B. (Guest)
on 2006-04-29 22:26
I have successfully used HABTM to create a many-to-one-to-many set of
rows in one step. Now, if two objects I want to associate already exist,
how do I create the join row? The Agile book mentions the
'push_with_attributes' method. The text says this method is useful for
adding additional attributes to the join row (in the example a 'read_at'
timestamp). I only require a simple two-key join row - is
'push_with_attributes' the way to go?

-Lindsay
Lindsay B. (Guest)
on 2006-04-29 22:30
Lindsay B. wrote:
> many-to-one-to-many set of rows

should read ' one-to-many-to-one rows'

-Lindsay
Lindsay B. (Guest)
on 2006-04-30 00:02
It's OK, I figured it out.

-Lindsay
Christer N. (Guest)
on 2006-04-30 13:41
Lindsay B. wrote:
> It's OK, I figured it out.
>
> -Lindsay

Please end your monolog in a proper way by stating your solution.
Lindsay B. (Guest)
on 2006-04-30 17:54
 > Please end your monolog in a proper way by stating your solution.

A bug in my model's validation prevented the join row from being
created. No solution as such.

- Lindsay
Chris H. (Guest)
on 2006-05-03 21:09
(Received via mailing list)
push with attributes is not what you want to use.  that's for when you
have
additional columns in your join table other than the two id columns for
the
joined tables.

example of what you want to do:

assumiing a habtm between foo and bar (using table bars_foos as join
tabled)

foo = Foo.find(1)
bar = Bar.find(1)


foo.bars << bar
# or you could do bar.foos << foo, same results

this will create the association in the join table.

http://api.rubyonrails.org/classes/ActiveRecord/As...

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