简体   繁体   中英

How to query a model based on multiple associated models

I have a rails application where I have following models -

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

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

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.

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. Also, don't forget to reset cache counter if you have some data in associated tables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM