Open Using Multiple Enums in a Single Model
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 i