Sql Rails通过关联连接
在RubyonRails中,我想在城市中找到雇主。 假设模型是这样设置的:Sql Rails通过关联连接,sql,ruby-on-rails,ruby-on-rails-3,join,ruby-on-rails-3.2,Sql,Ruby On Rails,Ruby On Rails 3,Join,Ruby On Rails 3.2,在RubyonRails中,我想在城市中找到雇主。 假设模型是这样设置的: 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 ha
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
我觉得我想找个雇主加入某个城市,但我不知道怎么做。如果人们直接属于城市,我可以加入雇主,加入那些城市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
你想在rails中实现这一点吗?为什么不直接使用他们的助手方法呢?很抱歉,你推荐哪种助手方法?为什么不通过
从雇主
遍历关系呢?就像你从城市
做的那样?Nvm,不确定做这件事的最佳方法是什么,sryAn雇主可能是多城市,因此,它不一定只属于一个城市。我可以创建一个联接表,但这似乎需要做很多工作。我可以给人们一个城市id,但这似乎不是标准化的方法,因为这些信息应该可以通过当前记录获得。好吧,我想这就是我要问的。为了弄清楚语法,最终的关联将如何确定一个特定的城市?假设我想找到所有雇佣芝加哥人的雇主,其模型ID为1?在其中添加where子句。where(“employers.city IN?AND employers.ID IN?,city,ID)另外,fwiw我正在重写一个名为searchlogic的gem来处理active record 3,应该很快就会完成。这使得在你的应用程序中进行这样的搜索变得非常简单。谢谢你的帮助。我选择了另一个答案,但从所有的回复中学到了很多。我将密切关注searchlogic,这是一项伟大的工作。@BKSpurgeon添加一个where子句。Ejoins({:people=>{:house=>{:郊区=>:city}}})。其中(“cities.name='Houston')
Wow。我完全不知道我可以建立这种关联。让我去实现它,我怀疑这正是我在寻找的答案,以解决未来类似的查询和问题。是的,在Rails 3.1中,嵌套的有很多:通过关系工作得很好。
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