TIL custom order with .in_order_of

epigene

Augusts Bautra

Posted on June 26, 2024

TIL custom order with .in_order_of

Sometimes you need a custom, semantic order for things, usually statuses, types. Oftentimes this is achieved with an SQL CASE statement:

sql = <<~SQL
  CASE
    WHEN status = 'active' THEN 0
    WHEN status = 'draft'  THEN 1    
    ELSE 99
  END
SQL 

order(sql, :id)
Enter fullscreen mode Exit fullscreen mode

Since at least Rails 7.1 there's a better way - in_order_of!

in_order_of(:status, [:active, :draft], filter: false).order(:id)
Enter fullscreen mode Exit fullscreen mode

Interestingly, v7.1 guide does not list this method at all, but it's available in edge guide.

Small caveat emptor - the filter: false option does not seem to be available in v7.1 yet.

💖 💪 🙅 🚩
epigene
Augusts Bautra

Posted on June 26, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related