Rails Complex Order Query

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! 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s