How to use Enum attributes in Ruby on Rails?
Last Updated :
17 Jun, 2024
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.
Similar Reads
How to create API in Ruby on Rails? Building APIs with Ruby on Rails: A Step-by-Step GuideRuby on Rails (Rails) is a popular framework for web development, known for its convention over configuration approach. It also excels in creating robust and maintainable APIs (Application Programming Interfaces). APIs act as intermediaries, allo
3 min read
How to Create Button in Ruby on Rails? Ruby on Rails, commonly known as Rails, is a popular web application framework written in the Ruby programming language. It follows the Model-View-Controller (MVC) architectural pattern, which separates the application's data, logic, and user interface components. Rails emphasizes convention over co
7 min read
How to create model in Ruby on Rails? In Ruby on Rails, models are like the organizers of your data. They handle interactions with your database. Think of them as the brains of your application, responsible for managing and manipulating data. They represent the structure and behavior of the information your app works with. So, whenever
4 min read
How to create table in Ruby on Rails? In Ruby on Rails, creating tables involves using migrations, which are a powerful mechanism for managing database schema changes. Here's a detailed breakdown of the process: 1. Database Setup (Optional): While APIs can function without databases, many Rails applications use them for data persistence
3 min read
How to Set Cookie in Ruby on Rails? Cookies are small pieces of data that are sent from a website and stored on the user's computer by the user's web browser. They are commonly used for session management, user authentication, personalization, and tracking. In Ruby on Rails, you can use the 'cookies' object to set, read, and delete co
3 min read