Using Multiple Enums in a Single Model
Rails allows multiple enums in a single model, enabling complex state management.
Example: Managing User Role and Status
class User < ApplicationRecord
enum :status, { active: 0, inactive: 1, banned: 2 }
enum :role, { admin: 10, member: 11, guest: 12 }
end
Now, you can use methods like:
user = User.new(status: :active, role: :admin)
user.active? # => true
user.admin? # => true
Handling Overlapping Values
Ensure that integer values do not overlap between different enums:
enum :role, { admin: 0, editor: 1, viewer: 2 }
enum :status, { pending: 0, approved: 1, rejected: 2 } # Overlaps with role
This can lead to unexpected behavior when querying records.
Here, admin
and pending
both have the value 0
, causing confusion when querying records.
editor
and approved
share the value 1, leading to incorrect results.
Solution: Always use distinct integer values for different enums.
Using Prefixed/Suffixed Methods for Clarity
To avoid method name conflicts, use prefixes or suffixes:
class Order < ApplicationRecord
enum :state, { pending: 0, shipped: 1, delivered: 2 }, prefix: true
end
Now, Rails generates:
order.state_pending? # Instead of order.pending?
order.state_shipped!
This makes the method names clearer and avoids conflicts with other model attributes.