[英]How to query a model based on multiple associated models
I have a rails application where I have following models - 我有一个Rails应用程序,其中有以下模型-
City, Hotel, Restaurant, Park. 城市,酒店,餐厅,公园。
Associations are like this - 协会是这样的-
class City < ActiveRecord::Base
has_many :hotels
has_many :restaurants
has_many :parks
end
I want to find all cities that have at least one hotel or restaurant or Park. 我想查找所有至少拥有一个酒店或餐厅或公园的城市。
How do I write single query to fetch such cities ? 如何编写单个查询来获取此类城市?
For Rails 5, you can use like below 对于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})))
For lower version of rails , you need to use arel_table 对于较低版本的rails,您需要使用arel_table
The City model doesn't have any information about related stuff. 城市模型没有有关任何相关信息。 You need to select the data from hotel/park/etc. 您需要从酒店/公园/等中选择数据。
Use AR's includes
to find the all Cities with specified relations. 使用AR的includes
查找具有指定关系的所有城市。
City.includes(:hotels, :restaurants, :parks)
Most appropriate solution would be using counter cache 最合适的解决方案是使用计数器缓存
Then you should be able to query like 然后您应该能够像
City.where('hotels_count > 0 OR restaurants_count > 0 OR parks_count > 0')
PS This query can be re-written many ways eg use .or
method. PS该查询可以用多种方式.or
例如使用.or
方法。 Also, don't forget to reset cache counter if you have some data in associated tables. 此外,如果关联表中有一些数据,请不要忘记重置缓存计数器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.