简体   繁体   English

Rails通过关联加入

[英]Rails joins through association

In Ruby on Rails, I want to find employers in the city. 在Ruby on Rails中,我想找到这个城市的雇主。 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. 我觉得我想要某种雇主加入some_city.people,但我不知道如何做到这一点。 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. 如果人们直接属于城市,我可以将雇主加入到city_id所属的人群中,但我希望在没有直接加入的情况下找到相同的数据,我有点迷失。

Thank you. 谢谢。

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 }})

You can do the join like jvans has illustrated. 你可以像jvans所说的那样进行连接。 Or you can setup your relationships like the following: 或者您可以设置如下关系:

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

Then you can join City from Employer , and vice-versa, directly. 然后你可以直接从Employer加入City ,反之亦然。

For example: 例如:

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