33

在 Ruby on Rails 中,我想在城市中找到雇主。假设模型是这样设置的:

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

我觉得我想要某种雇主加入 some_city.people 但我不知道该怎么做。如果人们直接属于城市,我可以将 Employer 加入到 city_id 是某物的人,但我想在没有直接加入的情况下找到相同的数据,我有点迷茫。

谢谢你。

4

2 回答 2

46

使用嵌套连接

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

应该给你你正在寻找的连接表。如果您正在穿越另一个方向,您将使用复数名称

City.joins( :suburbs => {:households => {:people => :employers }})
于 2013-04-20T02:40:47.177 回答
24

您可以像 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

然后您可以直接加入Cityfrom 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
于 2013-04-20T02:53:18.543 回答