Rails 7
An update for enum

Mar 2, 2021

It looks like a new syntax for declaring enums in your models has been introduced. Instead of passing the name and values as a key/value pair, it can now be passed as two separate arguments instead. Not a big change in itself but what this enables is in my opinion a more intuitive way to pass additional options.

Up until now, you would typically declare it something like this

class Product < ActiveRecord::Base
  enum status: [ :draft, :active, :archived ], _prefix: true, _scopes: true, _default: :draft
end

But going forward, you can also (both ways seem possible for now) declare it in the following way

class Product < ActiveRecord::Base
  enum :status, [ :draft, :active, :archived ], prefix: true, scopes: true, default: :draft
end

Notice how there is no leading underscore in the optional arguments.

And just to give you a refresher, both of the above syntaxes will result in the following instance methods and scopes:

 # Instance methods
@product.status_draft?
@product.status_draft!
@product.status_active?
@product.status_active!
@product.status_archived?
@product.status_archived!

 # Scopes
Product.status_draft
Product.status_active
Product.status_archived

Thank you for reading!

Happy Coding!