Today gonna talk about Rails Complex Query for ordering. Here’s a simple query order by status

@events = @events.order("status DESC")

But what happen if you want to make the query to order the status in a specific sequence. Here’s the example:

@events = @events.order("
CASE
WHEN events.status = 'NEW' THEN 0
WHEN events.status = 'OPEN' THEN 1
WHEN events.status = 'UPDATED' THEN 2
WHEN events.status = 'WAITING' THEN 3
WHEN events.status = 'ABANDONED' THEN 4
ELSE 5
END")

Happy Hacking, Enjoy!🙂