Open In App

How to use Enum attributes in Ruby on Rails?

Last Updated : 17 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Enums in Ruby on Rails map a set of symbolic values to integers in the database, making the code more readable and easier to maintain.

Why Enums are Useful?

Enums provide

  • Readability: Use descriptive names instead of numbers.
  • Validation: Ensures only predefined values are used.
  • Convenience: Rails provides methods for setting and querying enum values.

Explain Adding an Enum to an Existing Table

To add an enum attribute to an existing table:

1. Create a Migration: Generate a migration to add an integer column for the enum.

rails generate migration AddStatusToCourses status:integer

2. Optionally, set a default value:

add_column :courses, :status, :integer, default: 0

3. Run the Migration:

rails db:migrate

4. Update the Model: Define the enum in your model.

class Course < ApplicationRecord
enum status: { pending: 0, active: 1, archived: 2 }
end

How to Create an Enum with a New Database Table?

1. When creating a new table, specify the enum attribute in the migration:

create_table :courses do |t|
t.integer :status, default: 0
t.timestamps
end

2. Define the enum in the model:

class Course < ApplicationRecord
enum status: { pending: 0, active: 1, archived: 2 }
end

How to Set an Enum Value?

Set the enum value using its symbolic name

course = Course.new
course.status = :active

Or directly when creating the record

course = Course.create(status: :active)

How to Check an Enum Value?

Rails provides helper methods to check the value of an enum

course.active?  # returns true if status is 'active'
course.pending? # returns true if status is 'pending'

Example

Here’s how the complete code might look

1. Migration File (db/migrate/xxxxxx_add_status_to_courses.rb):

Ruby
class AddStatusToCourses < ActiveRecord::Migration[6.0]
  def change
    add_column :courses, :status, :integer, default: 0
  end
end


2. Model File (app/models/course.rb):

Ruby
class Course < ApplicationRecord
  enum status: { pending: 0, active: 1, archived: 2 }
end


3. Using the Enum in Rails Console:

Ruby
# Creating a new course with default status
course = Course.create
puts course.status  # Output: "pending"

# Setting the status to 'active'
course.status = :active
course.save
puts course.status  # Output: "active"

# Checking the status
puts course.active?  # Output: true
puts course.pending? # Output: false

Conclusion

Enums in Rails offer a simple way to manage a set of related constants, improving code readability and reducing potential errors by enforcing valid values.


Next Article
Article Tags :

Similar Reads