Skip to content
Browse files

Fix ActiveRecord::Relation#unscope

I'm pretty confused about the addition of this method. The documentation
says that it was intended to allow the removal of values from the
default scope (in contrast to #except). However it behaves exactly the
same as except: (other than
having a slightly enhanced syntax).

The removal of the default scope is allowed by
94924dc, which was not a change we
could make until 4.1 due to the need to deprecate things. However after
that change #unscope still gives us nothing that #except doesn't already
give us.

However there *is* a desire to be able to unscope stuff in a way that
persists across merges, which would allow associations to be defined
which unscope stuff from the default scope of the associated model. E.g.

  has_many :comments, -> { unscope where: :trashed }

So that's what this change implements. I've also corrected the
documentation. I removed the guide references to #except as I think
unscope really supercedes #except now.

While we're here, there's also a potential desire to be able to write

  has_many :comments, -> { unscoped }

However, it doesn't make sense and would not be straightforward to
implement. While with #unscope we're specifying exactly what we want to
be removed from the relation, with "unscoped" we're just saying that we
want it to not have some things which were added earlier on by the
default scope. However in the case of an association, we surely don't
want *all* conditions to be removed, otherwise the above would just
become "SELECT * FROM comments" with no foreign key constraint.

To make the above work, we'd have to somehow tag the relation values
which get added when evaluating the default scope in order to
differentiate them from other relation values. Which is way too much
complexity and therefore not worth it when most use cases can be
satisfied with unscope.

Closes #10643, #11061.
  • Loading branch information...
1 parent da80061 commit 64b9e93bb571160315987862583a83222e506734 @jonleighton jonleighton committed Nov 20, 2013
5 activerecord/
@@ -1,3 +1,8 @@
+* Make ActiveRecord::Relation#unscope affect relations it is merged in
+ to.
+ *Jon Leighton*
* Use strings to represent non-string `order_values`.
*Yves Senn*
2 activerecord/lib/active_record/relation.rb
@@ -7,7 +7,7 @@ class Relation
MULTI_VALUE_METHODS = [:includes, :eager_load, :preload, :select, :group,
:order, :joins, :where, :having, :bind, :references,
- :extending]
+ :extending, :unscope]
SINGLE_VALUE_METHODS = [:limit, :offset, :lock, :readonly, :from, :reordering,
:reverse_order, :distinct, :create_with, :uniq]
17 activerecord/lib/active_record/relation/query_methods.rb
@@ -341,20 +341,27 @@ def reorder!(*args) # :nodoc:
# User.where(name: "John", active: true).unscope(where: :name)
# == User.where(active: true)
- # Note that this method is more generalized than ActiveRecord::SpawnMethods#except
- # because #except will only affect a particular relation's values. It won't wipe
- # the order, grouping, etc. when that relation is merged. For example:
+ # This method is similar to <tt>except</tt>, but unlike
+ # <tt>except</tt>, it persists across merges:
- # Post.comments.except(:order)
+ # User.order('email').merge(User.except(:order))
+ # == User.order('email')
+ #
+ # User.order('email').merge(User.unscope(:order))
+ # == User.all
+ #
+ # This means it can be used in association definitions:
+ #
+ # has_many :comments, -> { unscope where: :trashed }
- # will still have an order if it comes from the default_scope on Comment.
def unscope(*args)
check_if_method_has_arguments!(:unscope, args)
def unscope!(*args) # :nodoc:
+ self.unscope_values += args
args.each do |scope|
case scope
9 activerecord/test/cases/associations/has_many_associations_test.rb
@@ -1761,4 +1761,13 @@ def test_collection_association_with_private_kernel_method
assert_equal 1, speedometer.minivans.to_a.size, "Only one association should be present:\n#{speedometer.minivans.to_a}"
assert_equal 1, speedometer.reload.minivans.to_a.size
+ test "can unscope the default scope of the associated model" do
+ car = Car.create!
+ bulb1 = Bulb.create! name: "defaulty", car: car
+ bulb2 = Bulb.create! name: "other", car: car
+ assert_equal [bulb1], car.bulbs
+ assert_equal [bulb1, bulb2], car.all_bulbs.sort_by(&:id)
+ end
2 activerecord/test/cases/relation/mutation_test.rb
@@ -20,7 +20,7 @@ def relation
@relation ||='posts'), Post.arel_table
- (Relation::MULTI_VALUE_METHODS - [:references, :extending, :order]).each do |method|
+ (Relation::MULTI_VALUE_METHODS - [:references, :extending, :order, :unscope]).each do |method|
test "##{method}!" do
assert relation.public_send("#{method}!", :foo).equal?(relation)
assert_equal [:foo], relation.public_send("#{method}_values")
6 activerecord/test/cases/scoping/default_scoping_test.rb
@@ -262,6 +262,12 @@ def test_unscope_errors_with_non_symbol_or_hash_arguments
+ def test_unscope_merging
+ merged = Developer.where(name: "Jamis").merge(Developer.unscope(:where))
+ assert merged.where_values.empty?
+ assert !merged.where(name: "Jon").where_values.empty?
+ end
def test_order_in_default_scope_should_not_prevail
expected = Developer.all.merge!(order: 'salary desc').to_a.collect { |dev| dev.salary }
received = DeveloperOrderedBySalary.all.merge!(order: 'salary').to_a.collect { |dev| dev.salary }
1 activerecord/test/models/car.rb
@@ -1,5 +1,6 @@
class Car < ActiveRecord::Base
has_many :bulbs
+ has_many :all_bulbs, -> { unscope where: :name }, class_name: "Bulb"
has_many :funky_bulbs, class_name: 'FunkyBulb', dependent: :destroy
has_many :foo_bulbs, -> { where(:name => 'foo') }, :class_name => "Bulb"
26 guides/source/
@@ -685,9 +685,9 @@ This will return single order objects for each day, but only those that are orde
Overriding Conditions
-### `except`
+### `unscope`
-You can specify certain conditions to be excepted by using the `except` method. For example:
+You can specify certain conditions to be removed using the `unscope` method. For example:
Post.where('id > 10').limit(20).order('id asc').except(:order)
@@ -698,30 +698,24 @@ The SQL that would be executed:
SELECT * FROM posts WHERE id > 10 LIMIT 20
-# Original query without `except`
+# Original query without `unscope`
SELECT * FROM posts WHERE id > 10 ORDER BY id asc LIMIT 20
-### `unscope`
-The `except` method does not work when the relation is merged. For example:
-will still have an order if the order comes from a default scope on Comment. In order to remove all ordering, even from relations which are merged in, use unscope as follows:
+You can additionally unscope specific where clauses. For example:
-Post.order('id DESC').limit(20).unscope(:order) = Post.limit(20)
-Post.order('id DESC').limit(20).unscope(:order, :limit) = Post.all
+Post.where(id: 10, trashed: false).unscope(where: :id)
+# => SELECT "posts".* FROM "posts" WHERE trashed = 0
-You can additionally unscope specific where clauses. For example:
+A relation which has used `unscope` will affect any relation it is
+merged in to:
-Post.where(id: 10).limit(1).unscope({ where: :id }, :limit).order('id DESC') = Post.order('id DESC')
+Post.order('id asc').merge(Post.unscope(:order))
+# => SELECT "posts".* FROM "posts"
### `only`

0 comments on commit 64b9e93

Please sign in to comment.
Something went wrong with that request. Please try again.