Read more

How to remove properties of ActiveRecord scopes

Arne Hartherz
October 09, 2015Software engineer at makandra GmbH

When dealing with AR scopes, you can remove conditions, order, etc by using the unscope method.

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

It is available on Rails 4+.


Examples

Consider an exemplary User class as follows. For the examples below, we will use a scope that applies all its constraints.

class User < ActiveRecord::Base
  scope :active, -> { where(locked: false) }
  scope :admins, -> { where(role: 'admin') }
  scope :ordered, -> { order(:name) }
end

users = User.active.admins.ordered

^
SELECT "users".* FROM "users" WHERE "users"."locked" = 'f' AND "users"."role" = 'admin' ORDER BY "users"."name" ASC

Removing conditions on one column:

users.unscope(where: :role)

^
SELECT "users".* FROM "users" WHERE "users"."locked" = 'f' ORDER BY "users"."name" ASC

Removing all conditions:

users.unscope(:where)

^
SELECT "users".* FROM "users" ORDER BY "users"."name" ASC

Removing order:

users.unscope(:order)

^
SELECT "users".* FROM "users" WHERE "users"."locked" = 'f' AND "users"."role" = 'admin'


Removing all properties

You can use unscoped (with a d) to strip the scope of any constraints.

users.unscoped

^
SELECT "users".* FROM "users"

While unscope was introduced with Rails 4, the unscoped method has been around since Rails 3.

Posted by Arne Hartherz to makandra dev (2015-10-09 19:16)