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 seem to be available in v7.1 yet.
Top comments (0)