[英]Rails query one model based on the lack of an associated model with conditions
[英]How to query a model based on multiple associated models
我有一個Rails應用程序,其中有以下模型-
城市,酒店,餐廳,公園。
協會是這樣的-
class City < ActiveRecord::Base
has_many :hotels
has_many :restaurants
has_many :parks
end
我想查找所有至少擁有一個酒店或餐廳或公園的城市。
如何編寫單個查詢來獲取此類城市?
對於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
城市模型沒有有關任何相關信息。 您需要從酒店/公園/等中選擇數據。
使用AR的includes
查找具有指定關系的所有城市。
City.includes(:hotels, :restaurants, :parks)
最合適的解決方案是使用計數器緩存
然后您應該能夠像
City.where('hotels_count > 0 OR restaurants_count > 0 OR parks_count > 0')
PS該查詢可以用多種方式.or
例如使用.or
方法。 此外,如果關聯表中有一些數據,請不要忘記重置緩存計數器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.