ActiveRecord::Enum
is an attribute where the values map to integers in the database and can be queried by name. Read more about enum here.
When we define an enum
in ActiveRecord
, it generates a set of methods to interact with these enum
values. These methods allow us to easily query
and manipulate the enum
values associated with a particular model instance.
Before
For instance, let’s assume we have a User
model with an enum field called role
:
class User < ApplicationRecord
enum :role, { admin: 0, moderator: 1, regular: 2 }
end
Currently, we expect to have methods like:
# Class methods / Scopes
User.roles
User.admins
User.moderators
User.regulars
.
.
# Instance methods
user = User.first
user.admin?
user.moderator?
user.regular?
.
.
user.admin!
user.moderator!
user.regular!
.
.
After
Rails 7.1 introduces an option to disable all auto generated methods of ActiveRecord.enum
with instance_methods: false
.
class User < ApplicationRecord
enum :role, { admin: 0, moderator: 1, regular: 2 }, instance_methods: false
end
user = User.first
user.role # => admin
user.admin?
# => `method_missing': undefined method `admin?' for #<User id: 1
user.regular!
# => `method_missing': undefined method `regular!' for #<User id: 1
Summary
To disable the default methods generated by ActiveRecord.enum
due to conflicts or unnecessary requirements, use instance_methods: false
. This option helps avoid the generation of conflicting or unnecessary enum methods.