14

I have a User model that has the following default_scope:

default_scope where(account_id: Account.current_account.id)

If I call User.all I always get a result based on the current account.

In some cases, for admin purposes, I'd like to bypass that scope and see all the users in the system regardless of the account.

Is there a way to do this?

Nathan
  • 7,627
  • 11
  • 46
  • 80

2 Answers2

28

Yes, with unscoped.

User.unscoped.all
MattAllegro
  • 6,455
  • 5
  • 45
  • 52
Dejan Simic
  • 7,820
  • 2
  • 28
  • 15
  • 2
    _Warning:_ check out the caveats in [this answer](http://stackoverflow.com/a/4166950/2859525)'s comments about using `unscoped` to solve this problem. – Todd Dec 30 '16 at 21:24
  • This isn't a great answer, we just experienced a situation in which `unscoped` totally ruined our result sets in testing. – barnacle.m May 26 '17 at 13:33
2

These days, the proper approach is to use unscope, which will only remove an explicit part of the scope. E.g.:

class User < ActiveRecord::Base
  default_scope where(account_id: Account.current_account.id)
  scope :all_accounts, -> { unscope(:account_id) }
end

This matters when you compose multiple scopes.

Of course, applying that kind of default scope in the first place is an anti-pattern in it self.

troelskn
  • 115,121
  • 27
  • 131
  • 155