This blog is part of our Rails 6 series.
When an enum attribute is defined on a model, Rails adds some default scopes to filter records based on values of enum on enum field.
Here is how enum scope can be used.
class Post < ActiveRecord::Base
enum status: %i[drafted active trashed]
end
Post.drafted # => where(status: :drafted)
Post.active # => where(status: :active)
In Rails 6, negative scopes are added on the enum values.
As mentioned by DHH in the pull request,
these negative scopes are convenient when you want to disallow access in controllers
Here is how they can be used.
class Post < ActiveRecord::Base
enum status: %i[drafted active trashed]
end
Post.not_drafted # => where.not(status: :drafted)
Post.not_active # => where.not(status: :active)
Check out the pull request for more details on this.

Written byAbhay Nikam
Related blogs
- 01Rails 6 adds support to persist timezones of Active JobSeptember 1, 2020 · Chetan Gawai
- 02Rails 6 adds including & excluding method on EnumerablesAugust 18, 2020 · Akhil Gautam
- 03Rails 6 fixes after_commit callback invocation bugFebruary 25, 2020 · Amit Choudhary
- 04Rails 6 adds rails db:prepare to migrate or setup a databaseDecember 10, 2019 · Akhil Gautam