Forum: Ruby on Rails Manipulating has_many :through associations

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Bradley M. (Guest)
on 2006-04-04 23:57
(Received via mailing list)

I haven't done any associations before, so please forgive my incorrect
use of terminology...

If I set up a has_many :through association, can I manipulate the
associated instances directly (like an Array), or do I need to
manipulate the join model?

For example, suppose I have two classes and the associated join model:

  class foo
    has_many :foo_bars
    has_many :bars, :through => :foo_bars

  class bar
    has_many :foo_bars
    has_many :foos, :through => :foo_bars

  class foo_bars
    belongs_to :foo
    belongs_to :bar

If I have an instance of foo and an instance of bar, how do I add the
association between the two of them?

  my_foo.bars << my_bar

or (inversely),

  my_bar.foos << my_foo

or do I somehow need to manipulate the join model explicitly?

Bradley M.
Vaishal S. (Guest)
on 2006-04-05 00:25
(Received via mailing list)
I think my_foo.foo_bars.create(:bars => my_bar) would work. Am not sure
that is the best way to do it though.
This topic is locked and can not be replied to.