A has_many :through (B, C)

Hi,

I’m wondring if it is possible to have a “has_many” through two things
at the same time.

For instance:

If I do this,


class A
has_many :blops # blobs have things
has_many :blups # blups has things too

has_many :things, :through => :blops
has_many :things, :through => :blups
end

only the “things” through “blups” get retrieved (only the last hmt is
considered by AR).

I tried “has_many :things, :through => [:blops, :blups]” too…

How can I do this and get all the things through blops and blups?

Thanks!

aurels

Aurels wrote:

class A
has_many :blops # blobs have things
has_many :blups # blups has things too

has_many :things, :through => :blops
has_many :things, :through => :blups
end

The blop things and the blup things are really different associations,
so you can do:

class A
has_many :blops
has_many :blups

has_many :blop_things, :through => :blops, :source => :thing
has_many :blup_things, :through => :blups, :source => :thing
end

If you need to access all of the things together, then you can add an
accessor:

def things
blop_things + blup_things
end

However you won’t be able to use the association methods on this (ie.,
#find, #sum, etc…)

You can use find… but it’ll be the ruby array find… not the
association AR find… and you can use SUM, as it is inside Enumerable
class, not the association proxy.

Julian

Learn Ruby on Rails! CHECK OUT THE FREE VIDS (LIMITED TIME) NEW VIDEO
OUT 3rd APRIL
http://sensei.zenunit.com/

Yes it works. But It would be great to be able to use #find
Thanks!

On Mar 31, 12:44 am, Mark B. [email protected]

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