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

MONGOID-5844 Fix counting bug in HABTM associations #5949

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

jamis
Copy link
Contributor

@jamis jamis commented Feb 4, 2025

In certain situations, calling #size on a HABTM association will return the wrong count.

This will happen if the association is initialized to a single element (forcing the _unloaded Criteria object to be scoped to that specific element) and then assigning an array of multiple (already-persisted) elements to the association, where one of the elements is the same element that already existed there.

In this case, _unloaded.count will return 1, and then the _added array will have two previously-persisted records. Naive implementations will thus return either 1, or 3, rather than the correct answer of 2. To get the correct answer, it is necessary to add a filter condition to _unloaded.count that excludes the records in the _added array.

In certain situations, calling #size on a HABTM association will
return the wrong count.

This will happen if the association is
initialized to a single element (forcing the _unloaded Criteria
object to be scoped to that specific element) and then assigning
an array of multiple (already-persisted) elements to the association,
where one of the elements is the same element that already existed
there.

In this case, `_unloaded.count` will return 1, and then the
_added array will have two previously-persisted records. Naive
implementations will thus return either 1, or 3, rather than the
correct answer of 2. To get the correct answer, it is necessary
to add a filter condition to `_unloaded.count` that excludes the
records in the `_added` array.
@jamis jamis requested a review from comandeo-mongo February 4, 2025 20:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants