How to Use Enum in Rails Model in Ruby on Rails
In Ruby on Rails, use
enum in your model to map integer values to human-readable symbols. Define it inside the model with a hash or array, like enum status: { active: 0, archived: 1 }, which lets you use methods like user.active? or User.archived.Syntax
The enum method in a Rails model defines a set of named values mapped to integers stored in the database. It takes a hash or array where keys are names and values are integers. Rails then creates helper methods for querying and setting these values.
- Model attribute: The database column storing the integer.
- Enum definition: Maps names to integers.
- Generated methods: Query scopes, predicate methods, and setters.
ruby
class YourModel < ApplicationRecord enum attribute_name: { name1: 0, name2: 1, name3: 2 } end
Example
This example shows a Task model with a status enum. It stores status as integers but lets you use readable names like :pending or :completed. You can query tasks by status or check a task's status with simple methods.
ruby
class Task < ApplicationRecord enum status: { pending: 0, in_progress: 1, completed: 2 } end # Usage examples: task = Task.new # Set status task.status = :pending # Check status puts task.pending? # true # Query all completed tasks completed_tasks = Task.completed
Output
true
Common Pitfalls
Common mistakes when using enums in Rails include:
- Not having the database column as an integer type.
- Changing enum values order or numbers after data is saved, which breaks existing records.
- Using strings instead of symbols when setting or querying enum values.
- Not handling invalid enum values, which can cause errors.
Always keep enum mappings stable and use symbols for clarity.
ruby
class User < ApplicationRecord # Wrong: Using string keys without symbols enum role: { 'admin' => 0, 'user' => 1 } # Right: enum role: { admin: 0, user: 1 } end
Quick Reference
| Feature | Description | Example |
|---|---|---|
| Define enum | Map names to integers in model | enum status: { active: 0, archived: 1 } |
| Set value | Assign enum using symbol | user.status = :active |
| Check value | Predicate method returns boolean | user.active? # true or false |
| Query scope | Get all records with enum value | User.archived |
| Database column | Must be integer type | t.integer :status |
Key Takeaways
Use
enum in Rails models to map integers to meaningful names for cleaner code.Always define the enum with symbols and keep the integer mappings stable to avoid data issues.
Rails auto-generates helpful methods like predicates and scopes for easy querying and checks.
Ensure the database column backing the enum is an integer type.
Use symbols when setting or checking enum values to prevent errors.