Skip to content

Commit 0a7cf5a

Browse files
authored
MONGOID-5208 fix error on reloading nil embedded document (#5116)
* MONGOID-5208 fix error on reloading nil embedded document * MONGOID-5208 give default return value * MONGOID-5208 update function to return nil * MONGOID-5208 change test description
1 parent bf28262 commit 0a7cf5a

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

lib/mongoid/reloadable.rb

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ def reload
2222
end
2323

2424
reloaded = _reload
25-
if Mongoid.raise_not_found_error && reloaded.empty?
25+
if Mongoid.raise_not_found_error && (reloaded.nil? || reloaded.empty?)
2626
raise Errors::DocumentNotFound.new(self.class, _id, _id)
2727
end
2828
@attributes = reloaded
@@ -78,7 +78,8 @@ def reload_embedded_document
7878
#
7979
# @param [ Hash ] attributes The document in the db.
8080
#
81-
# @return [ Hash ] The document's extracted attributes.
81+
# @return [ Hash | nil ] The document's extracted attributes or nil if the
82+
# document doesn't exist.
8283
def extract_embedded_attributes(attributes)
8384
atomic_position.split(".").inject(attributes) do |attrs, part|
8485
attrs = attrs[part =~ /\d/ ? part.to_i : part]

spec/mongoid/reloadable_spec.rb

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -311,6 +311,31 @@
311311
end
312312
end
313313

314+
context "when embedded document is nil" do
315+
316+
let(:palette) do
317+
Palette.new
318+
end
319+
320+
let(:canvas) do
321+
Canvas.create!(palette: palette)
322+
end
323+
324+
before do
325+
canvas.palette = nil
326+
end
327+
328+
let(:reload) do
329+
palette.reload
330+
end
331+
332+
it "raises a document not found error" do
333+
expect do
334+
reload
335+
end.to raise_error(Mongoid::Errors::DocumentNotFound, /Document\(s\) not found for class Palette with id\(s\)/)
336+
end
337+
end
338+
314339
context "with relational associations" do
315340

316341
let(:person) do

0 commit comments

Comments
 (0)