Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Get relationship on array of objects

I don't know if there's a good answer for this. Let's say I have:

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

I would like do something like:

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

And simply get all the photos back without iterating over them. I ask because each iteration is a DB call. Is there any good way that does a single DB call?

like image 505
Justin Avatar asked Nov 10 '11 02:11

Justin


1 Answers

The most straightforward way to do this is to use the eager loader:

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

That will fetch the users in one pass, then the relationships and their associated photos in another. You can wrap it all up into one call if you either use a JOIN or a subselect, it's your call, but it'll look something like this:

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

There's more information available in the Active Record Query Interface documentation in section 12.

like image 179
tadman Avatar answered Sep 21 '22 02:09

tadman