diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md
index 0cb1f05bb6925..33e8bbfb53fd1 100644
--- a/activerecord/CHANGELOG.md
+++ b/activerecord/CHANGELOG.md
@@ -1,3 +1,7 @@
+* Do not ignore the scoping with query methods in the scope block.
+
+ *Ryuta Kamizono*
+
* Allow aliased attributes to be used in `#update_columns` and `#update`.
*Gannon McGibbon*
diff --git a/activerecord/lib/active_record/relation/spawn_methods.rb b/activerecord/lib/active_record/relation/spawn_methods.rb
index 562e04194c491..7874c4c35af6e 100644
--- a/activerecord/lib/active_record/relation/spawn_methods.rb
+++ b/activerecord/lib/active_record/relation/spawn_methods.rb
@@ -8,7 +8,7 @@ module ActiveRecord
module SpawnMethods
# This is overridden by Associations::CollectionProxy
def spawn #:nodoc:
- clone
+ @delegate_to_klass ? klass.all : clone
end
# Merges in the conditions from other, if other is an ActiveRecord::Relation.
diff --git a/activerecord/test/cases/scoping/relation_scoping_test.rb b/activerecord/test/cases/scoping/relation_scoping_test.rb
index 9605afe806394..17caaedc98340 100644
--- a/activerecord/test/cases/scoping/relation_scoping_test.rb
+++ b/activerecord/test/cases/scoping/relation_scoping_test.rb
@@ -254,11 +254,16 @@ def test_scoping_respects_sti_constraint
end
end
- def test_scoping_works_in_the_scope_block
+ def test_scoping_with_klass_method_works_in_the_scope_block
expected = SpecialPostWithDefaultScope.unscoped.to_a
assert_equal expected, SpecialPostWithDefaultScope.unscoped_all
end
+ def test_scoping_with_query_method_works_in_the_scope_block
+ expected = SpecialPostWithDefaultScope.unscoped.where(author_id: 0).to_a
+ assert_equal expected, SpecialPostWithDefaultScope.authorless
+ end
+
def test_circular_joins_with_scoping_does_not_crash
posts = Post.joins(comments: :post).scoping do
Post.first(10)
diff --git a/activerecord/test/models/post.rb b/activerecord/test/models/post.rb
index 8e7ee02605295..f3d789a758cd8 100644
--- a/activerecord/test/models/post.rb
+++ b/activerecord/test/models/post.rb
@@ -254,6 +254,7 @@ class SpecialPostWithDefaultScope < ActiveRecord::Base
self.table_name = "posts"
default_scope { where(id: [1, 5, 6]) }
scope :unscoped_all, -> { unscoped { all } }
+ scope :authorless, -> { unscoped { where(author_id: 0) } }
end
class PostThatLoadsCommentsInAnAfterSaveHook < ActiveRecord::Base