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.
Ae03102311939454d2b7f1ca3139fd97?d=identicon&s=25 Lindsay Boyd (Guest)
on 2006-04-29 20: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
Ae03102311939454d2b7f1ca3139fd97?d=identicon&s=25 Lindsay Boyd (Guest)
on 2006-04-29 20:30
Lindsay Boyd wrote:
> many-to-one-to-many set of rows

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

-Lindsay
Ae03102311939454d2b7f1ca3139fd97?d=identicon&s=25 Lindsay Boyd (Guest)
on 2006-04-29 22:02
It's OK, I figured it out.

-Lindsay
Af95bdaf87958c40150b813e94381bfd?d=identicon&s=25 Christer Nilsson (christer)
on 2006-04-30 11:41
Lindsay Boyd wrote:
> It's OK, I figured it out.
>
> -Lindsay

Please end your monolog in a proper way by stating your solution.
Ae03102311939454d2b7f1ca3139fd97?d=identicon&s=25 Lindsay Boyd (Guest)
on 2006-04-30 15: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
A2c85dc5ee81b12e3cc0a6522e8d079d?d=identicon&s=25 Chris Hall (Guest)
on 2006-05-03 19: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.