Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to do a double has_many :through association in rails?

I have four models: a, b, c, d

here is what I want to do:

a has_many b, :through => c
a has_many d, :through => b

so that in the console I can then do:

a.b
a.b.first.d
a.d

currently the first two commands work but on the third I get an SQL error. it appears to be trying to go straight through b to get d and not picking up the fact that a -> b goes through c.

How to solve?

like image 953
istan Avatar asked Dec 01 '22 03:12

istan


1 Answers

Quick update on this for anyone that comes across it, this is possible after Rails 3.1: http://guides.rubyonrails.org/3_1_release_notes.html

In your example, here's how it would look like:

Class A
  has_many :c
  has_many :b, :through => :c, :source => :b
  has_many :d, :through => :b, :source => :d
end

Class C
  has_many :b
  has_many :d, :through => :b, :source => :d
end    

Class B
  has_many :d
end

Class D

end

Just to clarify!

like image 148
njorden Avatar answered Dec 04 '22 06:12

njorden