Rails 7 introduces new syntax for enum

Latest changes in Rails 7 introduces new syntax for defining an enum.

Before

The previous syntax includes the key value pair for the enum name, its enum values, and the options.

class Post < ActiveRecord::Base
  enum status: [ :draft, :published, :archived ], _prefix: true, _scopes: false
  enum category: [ :free, :premium ], _suffix: true, _default: :free
end

After

The new syntax has made the enum name and the values a separate argument and the enum options can be passed as key value pairs.

class Post < ActiveRecord::Base
  enum :status, [ :draft, :published, :archived ], prefix: true, scopes: false
  enum :category, [ :free, :premium ], suffix: true, default: :free
end

These changes also work with the hash syntax.

class Post < ActiveRecord::Base
  enum :status, { draft: 0, published: 1, archived: 2 }, prefix: true, scopes: false
  enum :category, { free: 0, premium: 1 }, suffix: true, default: :free
end

The following instance methods will be generated by rails as usual and there are no changes here:

  • status_draft?
  • status_draft!
  • status_published?
  • status_published!
  • status_archived?
  • status_archived!
  • free_category?
  • free_category!
  • premium_category?
  • premium_category!

The following scopes will also be created

  • free_category
  • premium_category

Note that the scopes for status won’t be created as we have provided scopes: false.

Notice the changes in the option keys:

Old Option New Option
_default default
_prefix prefix
_suffix suffix
_scopes scopes

Note: The previous syntax will keep working until it is deprecated.

Need help on your Ruby on Rails or React project?

Join Our Newsletter