Custom Status Ordering With Rails 7.1 And In_order_of Method
Custom semantic order with SQL CASE or Rails' in_order_of! Use `in_order_of(:status, [:active, :draft], filter: false).order(:id)` for a better way since Rails 7.1.
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)
Since at least Rails 7.1 there's a better way - in_order_of!
in_order_of(:status, [:active, :draft], filter: false).order(:id)
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 s...