Sorting Records Based on Enums

Sorting by enum values is useful when you need to display records in a particular order.

User.order(:status) # Orders users by status (0 → active, 1 → inactive, 2 → banned)

For custom sorting, define a scope:

scope :ordered_by_status, -> { order(Arel.sql("CASE status WHEN 0 THEN 1 WHEN 1 THEN 2 ELSE 3 END")) }

Now, calling:

User.ordered_by_status

Sorts users based on a custom order.