Key Features of Enums
Enums provide many built-in features that simplify coding and reduce boilerplate. Let’s go over some of them.
1. Automatic Query Methods
When you define an enum, Rails automatically generates query methods for each value. Given:
class Post < ApplicationRecord
enum :visibility, { draft: 0, published: 1, archived: 2 }
end
You can query posts like this:
Post.draft # Returns all posts with visibility "draft"
Post.published # Returns all posts with visibility "published"
This eliminates the need for manually defining scopes like:
scope :draft, -> { where(visibility: 0) }
2. Boolean Helper Methods
Enums generate helper methods to check the current state of a record.
post = Post.new(visibility: :draft)
post.draft? # => true
post.published? # => false
3. State Transitions
With a simple method call, you can update an Enum attribute.
post.published! # Changes visibility to "published"
This eliminates the need for defining separate methods for updating states.
4. Using before_type_cast for Raw Values
Sometimes, you may need to access the integer value of an Enum instead of its symbolic representation.
post = Post.new(visibility: :draft)
post.visibility_before_type_cast # => 0
This is useful when working with APIs or raw database queries.