The Whiz of Oz
The Whiz of Oz

Reputation: 7043

Sorting Rails query results in a specific order and adding the rest to it

I have a specific order in which I want to show a number of my blog posts, but I'd also like to display regular blog posts after those selected ones.

So let's say I have posts [1, 7, 35, 36, 48] which I want to go first:

@selected_posts = Post.find([1, 7, 35, 36, 48])

But now I need to query for every other post, excluding those above:

@other_posts = Post.where.not(id: [1, 7, 35, 36, 48])

And now I need to combine those to maintain that order:

Post.find([1, 7, 35, 36, 48]) + Post.where.not(id: [1, 7, 35, 36, 48])

I'm using Postgres. Is it possible to do this in one query?

Upvotes: 0

Views: 52

Answers (1)

SteveTurczyn
SteveTurczyn

Reputation: 36860

You can do order by case...

priority_ids = [1, 7, 35, 36, 48]

@all_posts = Post.all.order("CASE WHEN id IN (#{priority_ids.join(',')}) THEN 1 ELSE 2 END")

(thanks to @DeepakMahakale for correction)

Upvotes: 1

Related Questions