DEV Community

Augusts Bautra
Augusts Bautra

Posted on

4

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.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay