method

unscoped

Importance_2
v3.1.0 - Show latest stable - 1 note - Class: ActiveRecord::Base
  • 1.0.0
  • 1.1.6
  • 1.2.6
  • 2.0.3
  • 2.1.0
  • 2.2.1
  • 2.3.8
  • 3.0.0 (0)
  • 3.0.9 (-2)
  • 3.1.0 (1)
  • 3.2.1
  • 3.2.8
  • 3.2.13
  • 4.0.2
  • 4.1.8
  • 4.2.1
  • 4.2.7
  • 4.2.9
  • 5.0.0.1
  • 5.1.7
  • 5.2.3
  • 6.0.0
  • 6.1.3.1
  • 6.1.7.7
  • 7.0.0
  • 7.1.3.2
  • 7.1.3.4
  • What's this?
unscoped() public

Returns a scope for this class without taking into account the default_scope.

class Post < ActiveRecord::Base
  def self.default_scope
    where :published => true
  end
end

Post.all          # Fires "SELECT * FROM posts WHERE published = true"
Post.unscoped.all # Fires "SELECT * FROM posts"

This method also accepts a block meaning that all queries inside the block will not use the default_scope:

Post.unscoped {
  Post.limit(10) # Fires "SELECT * FROM posts LIMIT 10"
}

It is recommended to use block form of unscoped because chaining unscoped with scope does not work. Assuming that published is a scope following two statements are same.

Post.unscoped.published Post.published

Show source
Register or log in to add new notes.
November 7, 2011 - (<= v3.0.9)
1 thank

unscoped.all / unscoped.count

At least in console, doing unscoped.all or unscoped.count initially returns expected results but, after you’ve added new records outside of the default_scope those two calls seem to use some cached values.

Therefore it should always be used with the block (as they sort of imply in the doc). unscoped { all } and unscoped {count }