diff --git a/lib/mongoid/reloadable.rb b/lib/mongoid/reloadable.rb index 9c6ff39e1b..6f66578c47 100644 --- a/lib/mongoid/reloadable.rb +++ b/lib/mongoid/reloadable.rb @@ -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 @@ -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] diff --git a/spec/mongoid/reloadable_spec.rb b/spec/mongoid/reloadable_spec.rb index 6c4dc1ed21..46de154a9a 100644 --- a/spec/mongoid/reloadable_spec.rb +++ b/spec/mongoid/reloadable_spec.rb @@ -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