BigBinary Blog

We write about Ruby on Rails, React.js, React Native, remote work, open source, engineering and design.

Rails 6 adds negative scopes on enum

This blog is part of our Rails 6 series.

Rails 6.0 was recently released.

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.

1class Post < ActiveRecord::Base
2  enum status: %i[drafted active trashed]
3end
4
5Post.drafted # => where(status: :drafted)
6Post.active  # => where(status: :active)
7

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.

1class Post < ActiveRecord::Base
2  enum status: %i[drafted active trashed]
3end
4
5Post.not_drafted # => where.not(status: :drafted)
6Post.not_active  # => where.not(status: :active)
7

Check out the pull request for more details on this.

Abhay Nikam in Rails 6
March 6, 2019
Share

Subscribe to our newsletter