Ordering records in Ruby

Order by value

Assume that we have model Post

class Post < ApplicationRecord
  enumerize :state, in: %w[submitted under_review published]

If we order by state, it would be:

#=> [:published, :submitted, :under_review]

But sometimes we would like to show posts in a different order (eg showing under_review posts first, then submitted and published ). So we can do something like this:

SORT_ORDER = %w[under_review submitted published]

# Rails 7
Post.in_order_of(:state, SORT_ORDER).all

# Older versions
Post.all.sort_by{ |post| SORT_ORDER.index(post.state) }