Skip to content

Commit 615620f

Browse files
MONGOID-5895 Make Reload Properly Update new_record (#6034) (#6037)
* Ensure reload properly handles instances where we create a new document, but set the ID to an existing one * Fix misplaced spec Co-authored-by: Matthew Livingstone <matthew.livingstone@clio.com>
1 parent 6fb3d41 commit 615620f

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

lib/mongoid/reloadable.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,12 @@ def reload
1717
reloaded = _reload
1818
check_for_deleted_document!(reloaded)
1919

20+
# In an instance where we create a new document, but set the ID to an existing one,
21+
# when the document is reloaded, we want to set new_record to false.
22+
# This is necessary otherwise saving will fail, as it will try to insert the document,
23+
# instead of attempting to update the existing document.
24+
@new_record = false unless reloaded.nil? || reloaded.empty?
25+
2026
reset_object!(reloaded)
2127

2228
run_callbacks(:find) unless _find_callbacks.empty?

spec/mongoid/reloadable_spec.rb

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,16 @@
134134

135135
agent.title.should == '007'
136136
end
137+
138+
it 'sets new_record to false' do
139+
expect(agent.new_record?).to be true
140+
141+
lambda do
142+
agent.reload
143+
end.should_not raise_error
144+
145+
expect(agent.new_record?).to be false
146+
end
137147
end
138148
end
139149

@@ -596,6 +606,20 @@
596606
band.id.should_not == original_id
597607
end
598608
end
609+
610+
context 'when there is no document matching our id' do
611+
let(:agent) { Agent.new(id: BSON::ObjectId.new) }
612+
613+
it 'does not set new_record to false' do
614+
expect(agent.new_record?).to be true
615+
616+
lambda do
617+
agent.reload
618+
end.should_not raise_error
619+
620+
expect(agent.new_record?).to be true
621+
end
622+
end
599623
end
600624

601625
context 'when document has referenced associations' do

0 commit comments

Comments
 (0)