Defining and Using Enums in Rails 8

Once the migration is in place, we can define the enum in the model using the new syntax:

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

This enables several powerful features:

1. Assigning Enum Values

You can assign enums using symbolic names:

user = User.new(status: :active)
user.status # => "active"

Or by directly using integer values:

user = User.new(status: 1)
user.status # => "inactive"

2. Checking Enum Values

Rails provides helper methods for checking enum values:

user.active?  # => true
user.banned?  # => false

These methods act as boolean flags, making conditional logic more readable.

3. Changing Enum Values

Enums allow state transitions by calling bang methods:

user.inactive!  # Updates status to "inactive"
user.status # => "inactive"

This eliminates the need for manually updating attributes like:

user.update(status: "inactive") # Not needed

Instead, user.inactive! is more concise and readable.

4. Querying with Enums

Rails automatically generates query methods for filtering records.

a) Fetching All Users with a Specific Status

User.active  # Returns all users with status "active"
User.banned  # Returns all users with status "banned"

This is equivalent to:

User.where(status: 0) # Fetch all active users

But using User.active is more expressive and readable.

b) Using Raw SQL Queries with Enums

Even though enums store integer values, Rails returns string representations when queried:

user = User.first
user.status  # => "active"

However, if you need the raw integer value, use:

user.status_before_type_cast  # => 0

This is useful when debugging queries.