Fix MONGOID-4874 Values seem to be lost when using add_to_set on a non-existent attribute on a loaded instance #4749
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
It seems when an instance is loaded from a database, its
attributes
method returns an instance of
BSON::Document
. This causes somesurprising behavior when we use
#add_to_set
on that loaded instance.When a value is assigned to a
BSON::Document
instance, it getsmodified:
https://github.com/mongodb/bson-ruby/blob/master/lib/bson/document.rb#L87-L89
During modification, the attribute loses its reference to the original
value, however the
add_to_set
method relies on this reference:mongoid/lib/mongoid/persistable/pushable.rb
Lines 27 to 31 in 136ccbc
Since that reference is broken, it no longer update the instance's
attribute and the value is lost in memory, though still retained in the
DB.
This ensures that the reference remains intact.