Skip to content

Commit 56b4fdb

Browse files
committed
Association loading isn't to be affected by null relation scoping
Follow up of rails#35868. Closes rails#19349.
1 parent e9d1d76 commit 56b4fdb

File tree

3 files changed

+31
-3
lines changed

3 files changed

+31
-3
lines changed

activerecord/lib/active_record/relation.rb

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -689,7 +689,7 @@ def inspect
689689
end
690690

691691
def empty_scope? # :nodoc:
692-
@values == klass.unscoped.values
692+
!null_relation? && @values == klass.unscoped.values
693693
end
694694

695695
def has_limit_or_offset? # :nodoc:
@@ -721,6 +721,10 @@ def load_records(records)
721721
@loaded = true
722722
end
723723

724+
def null_relation? # :nodoc:
725+
is_a?(NullRelation)
726+
end
727+
724728
private
725729
def already_in_scope?
726730
@delegate_to_klass && begin
@@ -770,7 +774,7 @@ def exec_queries(&block)
770774
@records =
771775
if eager_loading?
772776
apply_join_dependency do |relation, join_dependency|
773-
if ActiveRecord::NullRelation === relation
777+
if relation.null_relation?
774778
[]
775779
else
776780
relation = join_dependency.apply_column_aliases(relation)

activerecord/lib/active_record/scoping/named.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ def default_scoped(scope = relation) # :nodoc:
5858
end
5959

6060
def default_extensions # :nodoc:
61-
if scope = current_scope || build_default_scope
61+
if scope = scope_for_association || build_default_scope
6262
scope.extensions
6363
else
6464
[]

activerecord/test/cases/scoping/relation_scoping_test.rb

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -421,6 +421,18 @@ def test_nested_scope_finder
421421
end
422422
end
423423

424+
def test_none_scoping
425+
Comment.none.scoping do
426+
assert_equal 2, @welcome.comments.count
427+
assert_equal "a comment...", @welcome.comments.what_are_you
428+
end
429+
430+
Comment.where("1=1").scoping do
431+
assert_equal 2, @welcome.comments.count
432+
assert_equal "a comment...", @welcome.comments.what_are_you
433+
end
434+
end
435+
424436
def test_should_maintain_default_scope_on_associations
425437
magician = BadReference.find(1)
426438
assert_equal [magician], people(:michael).bad_references
@@ -461,4 +473,16 @@ def test_nested_scope_finder
461473
assert_equal "a category...", @welcome.categories.what_are_you
462474
end
463475
end
476+
477+
def test_none_scoping
478+
Category.none.scoping do
479+
assert_equal 2, @welcome.categories.count
480+
assert_equal "a category...", @welcome.categories.what_are_you
481+
end
482+
483+
Category.where("1=1").scoping do
484+
assert_equal 2, @welcome.categories.count
485+
assert_equal "a category...", @welcome.categories.what_are_you
486+
end
487+
end
464488
end

0 commit comments

Comments
 (0)