Merge pull request #45244 from luanzeba/association_size_on_scoped_relations
Clear out target when no new records
This commit is contained in:
commit
5fae32e564
@ -81,10 +81,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
|
||||
|
@ -322,6 +322,20 @@ def test_target_merging_recognizes_updated_in_memory_records
|
||||
|
||||
assert_not_empty member.favorite_memberships.to_a
|
||||
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
|
||||
|
Loading…
Reference in New Issue
Block a user