Querying Records Using Enum Methods
Rails automatically generates query methods based on enum values. These methods help retrieve records more concisely.
Basic Queries Using Enum Methods
Consider the following User
model:
class User < ApplicationRecord
enum :status, { active: 0, inactive: 1, banned: 2 }
end
Now, Rails provides dynamic methods for querying:
User.active # Fetches all users with status "active"
User.inactive # Fetches all users with status "inactive"
User.banned # Fetches all users with status "banned"
This is equivalent to writing:
User.where(status: :active)
User.where(status: :inactive)
Checking a Single Record’s Status
user = User.find(1)
user.active? # => true if user is active
user.banned? # => true if user is banned