Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clear out target when no new records #45244

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
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 @@ -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
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm having a hard time reasoning about why the size of member.favorite_memberships.size is 0. The count of member.favorite_memberships.count is 1, right? Shouldn't the addition of a persisted record to the relation therefore change the size to 1 as well? we're coming across this case where we are surprised that the following is now true

    membership = member.favorite_memberships.create!
    refute_included membership, member.favorite_memberships

end
end

class OverridingAssociationsTest < ActiveRecord::TestCase
Expand Down