Rails: getting relationships over an array of objects

I do not know if there is a good answer for this. Let's say I have:

users = User.where(:location => "Utopia") #=> Returns [user1,user2,user3,user4]

I would like to do something like:

users.photos #=> Returns all photos this group of users has

And just return all the photos without repeating them. I ask because each iteration is a DB call. Is there a good way that one DB call is made?

+5
source share
1 answer

The easiest way to do this is to use a bootloader:

users = User.where(:location => 'Utopia').includes(:photos)

This will allow users in one pass, and then the relationship and related photos in another. You can combine all this into one call, if you use either JOINor a subtitle, this is your call, but it will look something like this:

photos = Photo.includes(:user).where('users.location' => 'Utopia')

Active Record 12.

+5

All Articles