Skip to content

MONGOID-5208 fix error on reloading nil embedded document #5116

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Dec 30, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions lib/mongoid/reloadable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def reload
end

reloaded = _reload
if Mongoid.raise_not_found_error && reloaded.empty?
if Mongoid.raise_not_found_error && (reloaded.nil? || reloaded.empty?)
raise Errors::DocumentNotFound.new(self.class, _id, _id)
end
@attributes = reloaded
Expand Down Expand Up @@ -78,7 +78,8 @@ def reload_embedded_document
#
# @param [ Hash ] attributes The document in the db.
#
# @return [ Hash ] The document's extracted attributes.
# @return [ Hash | nil ] The document's extracted attributes or nil if the
# document doesn't exist.
def extract_embedded_attributes(attributes)
atomic_position.split(".").inject(attributes) do |attrs, part|
attrs = attrs[part =~ /\d/ ? part.to_i : part]
Expand Down
25 changes: 25 additions & 0 deletions spec/mongoid/reloadable_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,31 @@
end
end

context "when embedded document is nil" do

let(:palette) do
Palette.new
end

let(:canvas) do
Canvas.create!(palette: palette)
end

before do
canvas.palette = nil
end

let(:reload) do
palette.reload
end

it "raises a document not found error" do
expect do
reload
end.to raise_error(Mongoid::Errors::DocumentNotFound, /Document\(s\) not found for class Palette with id\(s\)/)
end
end

context "with relational associations" do

let(:person) do
Expand Down