Skip to content

giljr/How_To_use_Enum

Repository files navigation

🎯 Mastering Enums in Rails 8

A Practical Guide to Simplify and Enhance Your ActiveRecord Models
#Rails8Series — Episode 7
✍️ by J3
🗓️ Jan 23, 2025


🚀 Introduction

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


🛠️ How to Use Enums in Rails

0. Create the Demo App

rails new enum_demo
cd enum_demo

1. Generate Task Scaffold

rails 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

2. Define Enums in the Model

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.

3. Seed the Database

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

4. Enum Helpers

Task.pending         # Scope for all pending tasks
Task.in_progress     # Scope for in-progress tasks
task = Task.new(title: "New Task")
task.status          # => "pending" (default)
task.status = :completed
task.completed?      # => true
task.status_before_type_cast # => 2

5. I18n Support

Define 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}")
end

Use it like:

task.human_status # => "In Progress"

6. Advanced Enum Options

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.

⚠️ Limitations

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 🧑‍💻

License

MIT

Releases

No releases published

Packages

 
 
 

Contributors