Skip to content

Commit 3036490

Browse files
sgrifrafaelfranca
authored andcommitted
Merge pull request rails#19783 from vngrs/raise_error_on_touch_if_object_is_stale
Raise StaleObjectError if touched object is stale and locking is enabled
1 parent b0994d0 commit 3036490

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

activerecord/lib/active_record/persistence.rb

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -466,11 +466,23 @@ def touch(*names)
466466
changes[column] = write_attribute(column, current_time)
467467
end
468468

469-
changes[self.class.locking_column] = increment_lock if locking_enabled?
470-
471469
clear_attribute_changes(changes.keys)
472470
primary_key = self.class.primary_key
473-
self.class.unscoped.where(primary_key => self[primary_key]).update_all(changes) == 1
471+
scope = self.class.unscoped.where(primary_key => _read_attribute(primary_key))
472+
473+
if locking_enabled?
474+
locking_column = self.class.locking_column
475+
scope = scope.where(locking_column => _read_attribute(locking_column))
476+
changes[locking_column] = increment_lock
477+
end
478+
479+
result = scope.update_all(changes) == 1
480+
481+
if !result && locking_enabled?
482+
raise ActiveRecord::StaleObjectError.new(self, "touch")
483+
end
484+
485+
result
474486
else
475487
true
476488
end

activerecord/test/cases/locking_test.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,16 @@ def test_touch_existing_lock
177177
assert_equal 1, p1.lock_version
178178
end
179179

180+
def test_touch_stale_object
181+
person = Person.create!(first_name: 'Mehmet Emin')
182+
stale_person = Person.find(person.id)
183+
person.update_attribute(:gender, 'M')
184+
185+
assert_raises(ActiveRecord::StaleObjectError) do
186+
stale_person.touch
187+
end
188+
end
189+
180190
def test_lock_column_name_existing
181191
t1 = LegacyThing.find(1)
182192
t2 = LegacyThing.find(1)

0 commit comments

Comments
 (0)