Skip to content

Commit 86c829a

Browse files
MONGOID-5797 Fix accessing parent when projected (mongodb#5847) (mongodb#5850)
1 parent 25a2ce3 commit 86c829a

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
@@ -115,7 +115,11 @@ def get_relation(name, association, object, reload = false)
115115
# during binding or when cascading callbacks. Whenever we retrieve
116116
# associations within the codebase, we use without_autobuild.
117117
if !without_autobuild? && association.embedded? && attribute_missing?(field_name)
118-
raise ActiveModel::MissingAttributeError, "Missing attribute: '#{field_name}'"
118+
# We always allow accessing the parent document of an embedded one.
119+
try_get_parent = association.is_a?(
120+
Mongoid::Association::Embedded::EmbeddedIn
121+
) && field_name == association.key
122+
raise ActiveModel::MissingAttributeError, "Missing attribute: '#{field_name}'" unless try_get_parent
119123
end
120124

121125
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
@@ -27,6 +27,10 @@
2727
expect(legislator.attributes.keys).to eq(['_id', 'a'])
2828
end
2929

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

0 commit comments

Comments
 (0)