簡體   English   中英

Rails通過關聯加入

[英]Rails joins through association

在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,但我不知道如何做到這一點。 如果人們直接屬於城市,我可以將雇主加入到city_id所屬的人群中,但我希望在沒有直接加入的情況下找到相同的數據,我有點迷失。

謝謝。

使用嵌套連接

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

應該給你你正在尋找的聯接表。 如果您正在遍歷另一個方向,則使用復數名稱

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

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

然后你可以直接從Employer加入City ,反之亦然。

例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM