Negative Scope in Rails 6

Rails 6 Tutorials - SapidLabs

Rails 6 Adds negative scope for all enum values

Rails 6 provide with some extra stuffs added to it lately which simplifies the daily tasks. If you have used rails previously like we did very often, then you must be knowing that we quite often, stumbled upon a situation where we need Negative scope for a defined enum values.

Example: Say you have a Post model in your rails application, and you have serveral states of the Post example :draft, :published and :trashed. Now, you want to query all the posts that are not published or not in draft or not in trash state.

Easy ! Isn’t it ? Kids stuff !

  Post.where.not(state: :draft)
  Post.where.not(state: :published)
  Post.where.not(state: :trashed)

Imagine a situation where there are 10 different states for your any defined entity. You will definitely end up defining tens of different methods based your requirements. Isn’t it?

Here, Rails 6 comes to the rescue. Rails 6 ships with an predefined negative scopes, pre-fixed with not_{enum_name}. So, above snippet can be re-written as:

  Post.where.not(state: :draft) becomes Post.not_draft
  Post.where.not(state: :published) becomes Post.not_published
  Post.where.not(state: :trashed) becomes Post.not_trashed

Super easy and saves some time as well.

Pull Request

Recommended Posts

Default Enum in Rails 6
Rails 6 provides a way to define default enum value. Let’s see how it works...
Ruby 2.7 adds Enumerable#tally
After introducing the Enumerable#tally method in Ruby 2.7-preview updates. #tally as the name suggests gives...
How to rename column name in Rails
Rails rename_column Rails provides a simple method rename_column which can be used in a migration....