From 260d3f261005242c05f0cd5abbb767ce86cb84be Mon Sep 17 00:00:00 2001 From: Dmitry Rybakov <160598371+comandeo-mongo@users.noreply.github.com> Date: Thu, 1 Aug 2024 16:54:00 +0200 Subject: [PATCH] MONGOID-5797 Fix accessing parent when projected (#5847) (#5849) --- lib/mongoid/association/accessors.rb | 6 +++++- spec/mongoid/association/embedded/embeds_many_query_spec.rb | 4 ++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/lib/mongoid/association/accessors.rb b/lib/mongoid/association/accessors.rb index 16a5b0c0df..06889a8551 100644 --- a/lib/mongoid/association/accessors.rb +++ b/lib/mongoid/association/accessors.rb @@ -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 diff --git a/spec/mongoid/association/embedded/embeds_many_query_spec.rb b/spec/mongoid/association/embedded/embeds_many_query_spec.rb index 8d46aa6220..5332e7429b 100644 --- a/spec/mongoid/association/embedded/embeds_many_query_spec.rb +++ b/spec/mongoid/association/embedded/embeds_many_query_spec.rb @@ -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