Rails 6 adds negative scopes for all enum values

Rails 6 adds negative scopes for all enum values

Default methods added by Enum

Rails allows adding enum to ActiveRecord models.

Enums allow declaring attributes, where the values map to integers in the database, but can be queried by name.

class Device < ApplicationRecord
  enum status: [ :active, :disabled ]
end

# This adds some convenience methods for us to use
# device.update! status: 0
device.active!
device.active? # => true
device.status  # => "active"

Along with these, Enum also add scope and query methods on the model:

# Scope methods
Device.active #=> All active devices
Device.disabled #=> All disabled devices
# We can query the enums like so
Device.where(status: :active) #=> All active devices

These scopes though are limited to positive queries. To fetch all inactive devices, or disabled devices, we have to query like so:

Device.where.not(status: :active) #=> All inactive devices
Device.where.not(status: :disabled)#=> All devices that are not disabled

Negative scopes

Rails 6 has now added convenience methods, to query the negative enum values.

# All inactive devices
# Before
Device.where.not(status: :active)
#After 
Device.not_active

# All devices that have not been disabled
# Before
Device.where.not(status: :disabled)
#After
Device.not_disabled

This gives us the ability to use a much cleaner syntax, rather than querying using where.not().

Need help on your Ruby on Rails or React project?

Join Our Newsletter