Sorting 2 arrays that have been added together

Posted by tyler on Stack Overflow See other posts from Stack Overflow or by tyler
Published on 2013-11-11T21:24:49Z Indexed on 2013/11/11 21:53 UTC
Read the original article Hit count: 266

In my app, users can create galleries that their work may or may not be in. Users have and belong to many Galleries, and each gallery has a 'creator' that is designated by the gallery's user_id field.

So to get the 5 latest galleries a user is in, I can do something like:

included_in = @user.galleries.order('created_at DESC').uniq.first(5)
# SELECT DISTINCT "galleries".* FROM "galleries" INNER JOIN "galleries_users" ON "galleries"."id" = "galleries_users"."gallery_id" WHERE "galleries_users"."user_id" = 10 ORDER BY created_at DESC LIMIT 5

and to get the 5 latest galleries they've created, I can do:

created = Gallery.where(user_id: id).order('created_at DESC').uniq.first(5)
# SELECT DISTINCT "galleries".* FROM "galleries" WHERE "galleries"."user_id" = 10 ORDER BY created_at DESC LIMIT 5

I want to display these two together, so that it's the 5 latest galleries that they've created OR they're in. Something like the equivalent of:

(included_in + created).order('created_at DESC').uniq.first(5)

Does anyone know how to construct an efficient query or post-query loop that does this?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby-on-rails-3