Skip to content

Commit

Permalink
MONGOID-5208 fix error on reloading nil embedded document (#5116)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
Neilshweky authored and p committed Jan 7, 2022
1 parent 90ed313 commit c8dc61e
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
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

0 comments on commit c8dc61e

Please sign in to comment.