Skip to content

Commit 69eaf1d

Browse files
MONGOID-5797 Fix accessing parent when projected (#5847)
1 parent 607a199 commit 69eaf1d

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed

lib/mongoid/association/accessors.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,11 @@ def get_relation(name, association, object, reload = false)
117117
# during binding or when cascading callbacks. Whenever we retrieve
118118
# associations within the codebase, we use without_autobuild.
119119
if !without_autobuild? && association.embedded? && attribute_missing?(field_name)
120-
raise Mongoid::Errors::AttributeNotLoaded.new(self.class, field_name)
120+
# We always allow accessing the parent document of an embedded one.
121+
try_get_parent = association.is_a?(
122+
Mongoid::Association::Embedded::EmbeddedIn
123+
) && field_name == association.key
124+
raise Mongoid::Errors::AttributeNotLoaded.new(self.class, field_name) unless try_get_parent
121125
end
122126

123127
if !reload && (value = ivar(name)) != false

spec/mongoid/association/embedded/embeds_many_query_spec.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,10 @@
2828
expect(legislator.attributes.keys).to eq(['_id', 'a'])
2929
end
3030

31+
it 'allows accessing the parent' do
32+
expect { legislator.congress }.not_to raise_error
33+
end
34+
3135
context 'when using only with $' do
3236
before do
3337
Patient.destroy_all

0 commit comments

Comments
 (0)