Skip to content

Commit

Permalink
MONGOID-5797 Fix accessing parent when projected (#5847) (#5849)
Browse files Browse the repository at this point in the history
  • Loading branch information
comandeo-mongo authored Aug 1, 2024
1 parent e128665 commit 260d3f2
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/mongoid/association/accessors.rb
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,11 @@ def get_relation(name, association, object, reload = false)
# during binding or when cascading callbacks. Whenever we retrieve
# associations within the codebase, we use without_autobuild.
if !without_autobuild? && association.embedded? && attribute_missing?(field_name)
raise ActiveModel::MissingAttributeError, "Missing attribute: '#{field_name}'"
# We always allow accessing the parent document of an embedded one.
try_get_parent = association.is_a?(
Mongoid::Association::Embedded::EmbeddedIn
) && field_name == association.key
raise ActiveModel::MissingAttributeError, "Missing attribute: '#{field_name}'" unless try_get_parent
end

if !reload && (value = ivar(name)) != false
Expand Down
4 changes: 4 additions & 0 deletions spec/mongoid/association/embedded/embeds_many_query_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@
expect(legislator.attributes.keys).to eq(['_id', 'a'])
end

it 'allows accessing the parent' do
expect { legislator.congress }.not_to raise_error
end

context 'when using only with $' do
before do
Patient.destroy_all
Expand Down

0 comments on commit 260d3f2

Please sign in to comment.