我想在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的人那里,但是我想在没有这种直接联系的情况下找到相同的数据,这让我有些困惑。

谢谢。

最佳答案

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

关于sql - Rails通过协会加入,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16115747/

10-13 02:16