From b3dd4a1a69797137dfd5711d9208647ac4cece88 Mon Sep 17 00:00:00 2001 From: Dmitry Rybakov Date: Fri, 10 Nov 2023 16:32:10 +0100 Subject: [PATCH] Wrap update in transaction --- lib/mongoid/persistable/updatable.rb | 12 ++++++++++-- spec/integration/validations_spec.rb | 6 ++++-- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/lib/mongoid/persistable/updatable.rb b/lib/mongoid/persistable/updatable.rb index 9dc5aeeaf7..34b5d2a777 100644 --- a/lib/mongoid/persistable/updatable.rb +++ b/lib/mongoid/persistable/updatable.rb @@ -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 diff --git a/spec/integration/validations_spec.rb b/spec/integration/validations_spec.rb index 135d167635..8f5d2989df 100644 --- a/spec/integration/validations_spec.rb +++ b/spec/integration/validations_spec.rb @@ -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 @@ -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