Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions lib/mongoid/reloadable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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?
Expand Down
24 changes: 24 additions & 0 deletions spec/mongoid/reloadable_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down