Order by two columns in Rails
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

I want to show posts that have received any number of "likes" first, and second, order by "points".

I don't want to sort on the actual "like" count at all, just the fact that they are above zero.

So, the first group of records will be "liked" by any non-zero number of people, and will be ordered by points received, in descending order.

After that, the non-liked records will be shown, also in descending order of "points".

Something like Post.order("like is not 0", points: :desc)

Edit: keeping it as one query as above is important, so pagination can be added smoothly.


Can you include an example Post array ?
Titus 9 months ago
Post is actually a made-up example. I'd just like to sort on an integer column, but treat all values greater than 0 as the same.
cchung 9 months ago
Wouldn't Post.order(likes: :desc, points: :desc) do that ?
Titus 9 months ago
@titus Almost, except that posts with more likes would appear first. I want posts with any amount of likes to appear before likeless posts, and then rank on points.
cchung 9 months ago
awarded to robinvdijk

Crowdsource coding tasks.

1 Solution

Winning solution

What about

Post.order('likes = 0, points DESC')

This sorts the liked posts by points in descending order of points, followed by unliked posts in descending order of points.

View Timeline