Rails 7 introduces new syntax for enum
source link: https://blog.saeloun.com/2021/02/26/rails-introduces-new-syntax-for-enum
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
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.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK