Preventing Invalid Assignments
By default, Rails allows direct assignment using integers:
user = User.new(status: 99) # This bypasses enum keys
To prevent this, override the setter method:
class User < ApplicationRecord
enum :status, { active: 0, inactive: 1, suspended: 2 }
def status=(value)
super(self.class.statuses[value.to_s] || value) if self.class.statuses.keys.include?(value.to_s)
end
end
Now, assigning user.status = :invalid_value
will not set an incorrect integer.