Rails,通过相关记录查找。

时间:2014-06-02 07:12:43

标签: ruby-on-rails activerecord ruby-on-rails-4

在我的应用程序中,我有两个模型:

class Address < ActiveRecord::Base
  belongs_to :location
end

class Location < ActiveRecord::Base
  #it has field city:string
  has_one :address
end

现在我想找到所有解决城市字段的地点都有价值:“测试”。我怎样才能做到这一点?提前谢谢。

3 个答案:

答案 0 :(得分:5)

Location.includes(:address).where(city: "test")

答案 1 :(得分:3)

由于没有其他人愿意解释您为何使用includes vs joins

假设数据:

addr1 = Address.create(street: "1 Unique Street", city: "test")
addr2 = Address.create(street: "2 Unique Street", city: "test")
Location.create(name: "Location 1", address: addr1)

连接:

Location.joins(:address).where(addresses: { city: "test" })

# performs INNER JOIN
#> [#<Location id: 1, name: "Location 1">,
     #<Location id: 1, name: "Location 1">]

包括:

Location.includes(:address).where(addresses: { city: "test" })

# performs LEFT OUTER JOIN
#> [#<Location id: 1, name: "Location 1">]

如果您使用joins,请使用distinct

Location.joins(:address).where(addresses: { city: "test" }).distinct(:location)

#> [#<Location id: 1, name: "Location 1">]

原因是因为INNER JOIN执行了joins。请在此处查看更多信息:What is the difference between "INNER JOIN" and "OUTER JOIN"?

答案 2 :(得分:1)

Location.joins(:address).where(addresses: {city: "test"})