【问题标题】:How to query a model based on multiple associated models如何根据多个关联模型查询模型
【发布时间】:2016-09-02 12:43:52
【问题描述】:
我有一个 Rails 应用程序,其中有以下模型 -
城市、酒店、餐厅、公园。
联想是这样的——
class City < ActiveRecord::Base
has_many :hotels
has_many :restaurants
has_many :parks
end
我想查找至少拥有一家酒店或餐厅或公园的所有城市。
如何编写单个查询来获取此类城市?
【问题讨论】:
标签:
mysql
ruby-on-rails
activerecord
model
associations
【解决方案1】:
对于 Rails 5,你可以像下面这样使用
cities = City.includes(:hotels, :restaurants, :parks)
cities = ((cities.where.not(hotels: {id: nil})).or(cities.where.not(restaurants: {id: nil})).or(cities.where.not(parks: {id: nil})))
对于较低版本的 rails ,您需要使用 arel_table
【解决方案2】:
最合适的解决方案是使用counter cache
那你应该可以像这样查询
City.where('hotels_count > 0 OR restaurants_count > 0 OR parks_count > 0')
附:此查询可以通过多种方式重写,例如使用 .or 方法。另外,如果关联表中有一些数据,请不要忘记重置缓存计数器。
【解决方案3】:
城市模型没有任何相关信息。
您需要从酒店/公园/等中选择数据。
使用 AR 的includes 查找所有具有指定关系的城市。
City.includes(:hotels, :restaurants, :parks)