If I have a Model with a has_many
relationship, how can I retrieve all of the records that all of the records in my query point to?
Let's just say, buildings have a has_many relationship with rooms. Here's what I want to do:
Building.where(...query...).rooms.count
This is just an example. I might want to count them, or I might want an ActiveRecord of the rooms that belong to the buildings that match the query.
One way is this, but I'm wondering if there's a better way:
building_ids = Building.where(...query...).pluck(:id)
Room.where(building_id: building_ids).count
Using select
instead of pluck
will result in a single sql statement instead of two separate ones.
building_ids = Building.where(...).ids
Room.where(building_id: building_ids)
you can also use join
Room.joins(:building).where(building: { name: 'somename' })
I'd use the sum of the counter caches.
Add the counter cache colum in a migration:
add_column :buildings, :rooms_count, default: 0
Update the relation in Room:
belongs_to :building, counter_cache: true
Then you could do something like:
Building.sum(:rooms_count)
That'll avoid n+1 queries
More details here https://blog.appsignal.com/2018/06/19/activerecords-counter-cache.html
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.