Manipulating has_many :through associations


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.

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 forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs