Waves black and white pattern

How to Write a Clean Order By Case Query with Arel on Rails

You’re working on a feature and someone tells you that one of your models needs to be ordered based on some complicated rule. You realize you’ll need to write a complex order by query… Here’s how it usually goes: You think to yourself: “Should I write an order by case when statement? Maybe I’ll just add a little bit of SQL…" Two minutes later, you end up with a bunch of nested case when statements, subqueries, common table expressions, angry statements, shouting, and a whole lot of tears....

June 10, 2021 Â· 4 min Â· Thiago Araujo