vince
vince

Reputation: 2848

How to order twice in the same query

How do you order something twice in the same query? For example I can order search for the top ten tagged courses by

categories = Category.all.limit(10).order(tags_count: :desc)

I can also order them alphabetically by

categories = Category.all.order(title: :desc)

How do you order by title after the top ten tagged courses have been queried? I tried this but it didn't work

categories = Category.all.limit(10).order(tags_count: :desc).order(title: :desc)

Upvotes: 1

Views: 414

Answers (3)

vince
vince

Reputation: 2848

This is the query that worked for me. Thank you @SebastianPalma for your help!

Category.where(id: Category.order(tags_count: :desc).limit(10)).order(title: :desc)

Upvotes: 1

Gautam
Gautam

Reputation: 1812

You can try like this -

Category.order(tags_count: :desc, title: :desc).limit(10)

What this will do is that it will first sort based on the tags_count in descending order and then sort the sorted result set on title in descending order.Then take the first 10 results and return those.

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521093

You may try ordering by a raw SQL expression:

categories = Category.all.limit(10).order('tags_count desc, title desc')

Upvotes: 2

Related Questions