From cef1a337578b7cb5e0f61c70e7db31fcd78f9f13 Mon Sep 17 00:00:00 2001 From: Matthew Livingstone Date: Tue, 9 Sep 2025 13:01:26 -0400 Subject: [PATCH] MONGOID-5895 Make Reload Properly Update new_record (#6034) * Ensure reload properly handles instances where we create a new document, but set the ID to an existing one * Fix misplaced spec --- lib/mongoid/reloadable.rb | 6 ++++++ spec/mongoid/reloadable_spec.rb | 24 ++++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/lib/mongoid/reloadable.rb b/lib/mongoid/reloadable.rb index e90b72168b..6530814cb2 100644 --- a/lib/mongoid/reloadable.rb +++ b/lib/mongoid/reloadable.rb @@ -17,6 +17,12 @@ def reload reloaded = _reload check_for_deleted_document!(reloaded) + # In an instance where we create a new document, but set the ID to an existing one, + # when the document is reloaded, we want to set new_record to false. + # This is necessary otherwise saving will fail, as it will try to insert the document, + # instead of attempting to update the existing document. + @new_record = false unless reloaded.nil? || reloaded.empty? + reset_object!(reloaded) run_callbacks(:find) unless _find_callbacks.empty? diff --git a/spec/mongoid/reloadable_spec.rb b/spec/mongoid/reloadable_spec.rb index 825a42042f..8a71701c72 100644 --- a/spec/mongoid/reloadable_spec.rb +++ b/spec/mongoid/reloadable_spec.rb @@ -134,6 +134,16 @@ agent.title.should == '007' end + + it 'sets new_record to false' do + expect(agent.new_record?).to be true + + lambda do + agent.reload + end.should_not raise_error + + expect(agent.new_record?).to be false + end end end @@ -596,6 +606,20 @@ band.id.should_not == original_id end end + + context 'when there is no document matching our id' do + let(:agent) { Agent.new(id: BSON::ObjectId.new) } + + it 'does not set new_record to false' do + expect(agent.new_record?).to be true + + lambda do + agent.reload + end.should_not raise_error + + expect(agent.new_record?).to be true + end + end end context 'when document has referenced associations' do