jeudi 14 juillet 2016

Rails ActiveRecord Query with Joins / Group with first and last ordered objects

I want to be able to find and group likes for photos based on a collection they're in and associate with the collection id. For example, I would imagine writing something like:

photos.joins(:photoset).group(:photoset_id).order('photos.time_posted ASC').limit(1).pluck(:like_count)

and to have it result in:

{ 1=>80,2=>92, 3=>94 }

meaning that Photoset 1's first photo has 80 likes, Photoset 2's first photo has 92 likes, and Photoset 3's first photo has 94 likes.

Effectively, I could do this based on each Photoset, but I'd like to avoid an N+1 query issue...

Aucun commentaire:

Enregistrer un commentaire