您可以像 jvans 所说明的那样进行连接。或者您可以设置您的关系,如下所示:
class Employer < ActiveRecord::Base
has_many :people
has_many :households, through: :people
has_many :suburbs, through: :households
has_many :cities, through: :suburbs
end
class Person < ActiveRecord::Base
belongs_to :household
belongs_to :employer
end
class Household < ActiveRecord::Base
belongs_to :suburb
has_many :people
end
class Suburb < ActiveRecord::Base
belongs_to :city
has_many :households
has_many :people, through: :households
end
class City < ActiveRecord::Base
has_many :suburbs
has_many :households, through: :suburbs
has_many :people, through: :households
has_many :employers, through: :people
end
然后您可以直接加入City
from Employer
,反之亦然。
例如:
Employer.joins(:cities).where("cities.name = ?", "Houston").first
SELECT "employers".* FROM "employers"
INNER JOIN "people" ON "people"."employer_id" = "employers"."id"
INNER JOIN "households" ON "households"."id" = "people"."household_id"
INNER JOIN "suburbs" ON "suburbs"."id" = "households"."suburb_id"
INNER JOIN "cities" ON "cities"."id" = "suburbs"."city_id" WHERE (cities.name = 'Houston')
LIMIT 1