A Practical Guide to Simplify and Enhance Your ActiveRecord Models
#Rails8Series — Episode 7
✍️ by J3
🗓️ Jan 23, 2025
Enums in Rails 8 (and earlier versions) are a powerful ActiveRecord feature that allows you to define a set of named values for a model attribute. These symbolic names are internally mapped to integers in the database, making them ideal for representing fixed sets of options like statuses, roles, or categories.
This repository walks through everything you need to master enums in Rails 8, with real code examples and best practices.
📘 Official documentation:
👉 https://api.rubyonrails.org/classes/ActiveRecord/Enum.html
rails new enum_demo
cd enum_demorails g scaffold Task title:string content:text status:integer
Then edit your migration to set a default status:
db/migrate/xxxx_create_tasks.rb:
t.integer :status, default: 0
Update routes:
config/routes.rb
root "tasks#index"
Run the migration:
rails db:migrate
app/models/task.rb
class Task < ApplicationRecord
enum :status, { pending: 0, in_progress: 1, completed: 2 }
end✅ In Rails 8+, keyword arguments are deprecated for enums. Use the new API syntax as shown above.
db/seeds.rb
puts "Seeding tasks..."
statuses = [:pending, :in_progress, :completed]
task_number = 1
statuses.each do |status|
2.times do
Task.create!(
title: "Task ##{task_number}",
status: Task.statuses[status]
)
task_number += 1
end
end
puts "Seeded #{Task.count} tasks!"run:
rails db:seed
Task.pending # Scope for all pending tasks
Task.in_progress # Scope for in-progress taskstask = Task.new(title: "New Task")
task.status # => "pending" (default)
task.status = :completed
task.completed? # => true
task.status_before_type_cast # => 2Define translations in config/locales/en.yml:
en:
activerecord:
attributes:
task:
status:
pending: "Pending"
in_progress: "In Progress"
completed: "Completed"Access translations:
task = Task.find(1)
I18n.t("activerecord.attributes.task.status.#{task.status}") # => "Pending"Add a helper in your model:
def human_status
I18n.t("activerecord.attributes.task.status.#{status}")
endUse it like:
task.human_status # => "In Progress"
Custom Prefix or Suffix:
enum :status, { pending: 0, in_progress: 1, completed: 2 }, prefix: :task
This will generate:
task.task_pending?
task.task_completed?
Array Syntax (simpler):
enum :status, [:pending, :in_progress, :completed]
✅ Benefits
Readable: Symbols like :pending are more meaningful than raw integers.
Safe: Prevents invalid assignments.
Convenient: Auto-generates helpers and scopes.
Enums are stored as integers. Do not reorder values without migration or you risk data corruption.
Consider custom tables for more flexibility if you need editable sets.
📎 Wrap-Up
Enums in Rails 8 provide a clean and structured way to manage fixed sets of values. They integrate seamlessly with ActiveRecord and I18n, boosting both clarity and functionality.
Feel free to fork, star ⭐️, or contribute! 🧠 Dive into the full blog post on Medium
Happy coding! — J3 🧑💻