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)
  and
  Post.where.not(state: :published)
  and
  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
  and
  Post.where.not(state: :published) becomes Post.not_published
  and
  Post.where.not(state: :trashed) becomes Post.not_trashed


Super easy and saves some time as well.

Pull Request

Recommended Posts

Rails 5 adds OR Activerecord method
This or method was introduced in Rails 5, It returns a new ActiveRecord::Relation which is...
Descendants vs Subclasses in Ruby
Descendants has been a part of Rails ActiveSupport::DescendantsTracker for quite a while. However, Class#subsclasses is...
Ruby 3.1 adds subclasses method
Ruby 3.1 adds Class#subclasses method, which returns an array of subclasses directly inheriting from the...