Using Custom Scopes for Enum Queries

Sometimes, you may need more readable and reusable queries. You can define custom scopes for better clarity.

class User < ApplicationRecord
  enum :status, { active: 0, inactive: 1, banned: 2 }

  scope :recently_banned, -> { where(status: :banned).where("updated_at > ?", 1.week.ago) }
end

Now, you can use:

User.recently_banned

This is equivalent to:

User.where(status: :banned).where("updated_at > ?", 1.week.ago)

Chaining Scopes and Enum Queries

You can chain multiple scopes together:

User.active.recently_banned

This filters only active users who were also recently banned.