Rails joins through association

spitfire109 picture spitfire109 · Apr 20, 2013 · Viewed 33k times · Source

In Ruby on Rails, I want to find employers in the city. Lets say the models are set up this way:

City
has_many :suburbs
has_many :households, :through => suburbs
has_many :people, :through => suburbs

Suburb
has_many :households
has_many people, :through => households
belongs_to :city


Household
has_many :people
belongs_to :suburb

People
belongs_to :household
belongs_to :employer


Employer
has_many :people

I feel like I want some sort of Employer joins some_city.people but I don't know how to do this. If people belonged directly to cities, I could join Employer to people where city_id is something, but I want to find the same data without that direct join and I am a little lost.

Thank you.

Answer

jvans picture jvans · Apr 20, 2013

Use nested joins

Employer.joins({:people => {:household => {:suburb => :city}}}) 

should give you the join table you're looking. If you were traversing the other direction you would use plural names

City.joins( :suburbs => {:households => {:people => :employers }})