Skip to content

Commit

Permalink
Merge pull request rails#45244 from luanzeba/association_size_on_scop…
Browse files Browse the repository at this point in the history
…ed_relations

Clear out target when no new records

(cherry picked from commit 5fae32e)
  • Loading branch information
jonathanhefner committed Jun 22, 2022
1 parent fd8812b commit a388dfa
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,13 @@ def count_records
scope.count(:all)
end

# If there's nothing in the database and @target has no new records
# we are certain the current target is an empty array. This is a
# documented side-effect of the method that may avoid an extra SELECT.
loaded! if count == 0
# If there's nothing in the database, @target should only contain new
# records or be an empty array. This is a documented side-effect of
# the method that may avoid an extra SELECT.
if count == 0
target.select!(&:new_record?)
loaded!
end

[association_scope.limit_value, count].compact.min
end
Expand Down
14 changes: 14 additions & 0 deletions activerecord/test/cases/associations_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,20 @@ def test_target_merging_ignores_persisted_in_memory_records
assert_equal 1, david.thinking_posts.size
assert_equal 1, david.thinking_posts.to_a.size
end

def test_size_differentiates_between_new_and_persisted_in_memory_records_when_loaded_records_are_empty
member = members(:blarpy_winkup)
assert_empty member.favorite_memberships

membership = member.favorite_memberships.create!
membership.update!(favorite: false)

# CollectionAssociation#size has different behavior when loaded vs. non-loaded
# the first call will mark the association as loaded and the second call will
# take a different code path, so it's important to keep both assertions
assert_equal 0, member.favorite_memberships.size
assert_equal 0, member.favorite_memberships.size
end
end

class OverridingAssociationsTest < ActiveRecord::TestCase
Expand Down

0 comments on commit a388dfa

Please sign in to comment.