How to remove properties of ActiveRecord scopes

Posted . Visible to the public.

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

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.

Arne Hartherz
Last edit
Arne Hartherz
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2015-10-09 17:16)