Forum: Ruby on Rails Manipulating has_many :through associations

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.
6f94c45fd92acbb3e21c328f6b35298a?d=identicon&s=25 Bradley Mazurek (Guest)
on 2006-04-04 21:57
(Received via mailing list)
Hi,

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?

Thanks,
  Brad
--
Bradley Mazurek
82ee2cbbd7a6ea331728565f766b0ff3?d=identicon&s=25 Vaishal Sheth (Guest)
on 2006-04-04 22:25
(Received via mailing list)
I think my_foo.foo_bars.create(:bars => my_bar) would work. Am not sure
if
that is the best way to do it though.
This topic is locked and can not be replied to.