Skip to content

Commit

Permalink
Wrap update in transaction
Browse files Browse the repository at this point in the history
  • Loading branch information
comandeo-mongo committed Nov 10, 2023
1 parent a023a7c commit b3dd4a1
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
12 changes: 10 additions & 2 deletions lib/mongoid/persistable/updatable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,16 @@ def update_attribute(name, value)
#
# @return [ true | false ] True if validation passed, false if not.
def update(attributes = {})
assign_attributes(attributes)
save
self.class.with_session do |session|
session.with_transaction do
assign_attributes(attributes)
save.tap do |result|
session.abort_transaction unless result
end
end
end
rescue StandardError => e
false
end
alias :update_attributes :update

Expand Down
6 changes: 4 additions & 2 deletions spec/integration/validations_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
end

it 'does not persist the changes' do
expect { client.update!(companies: []) rescue nil }.not_to change { client.reload.companies }
client.update!(companies: []) rescue nil
expect(client.reload.companies).not_to be_empty
end
end
end
Expand All @@ -32,7 +33,8 @@
end

it 'does not persist the changes' do
expect { building.update!(apartments: []) rescue nil }.not_to change { building.reload.apartments }
building.update!(apartments: []) rescue nil
expect(building.reload.apartments).not_to be_empty
end
end
end
Expand Down

0 comments on commit b3dd4a1

Please sign in to comment.