提交 9721b45b 编写于 作者: S Sean Griffin

Merge pull request #19783 from vngrs/raise_error_on_touch_if_object_is_stale

Raise StaleObjectError if touched object is stale and locking is enabled
......@@ -477,11 +477,23 @@ def touch(*names, time: nil)
changes[column] = write_attribute(column, time)
end
changes[self.class.locking_column] = increment_lock if locking_enabled?
clear_attribute_changes(changes.keys)
primary_key = self.class.primary_key
self.class.unscoped.where(primary_key => self[primary_key]).update_all(changes) == 1
scope = self.class.unscoped.where(primary_key => id)
if locking_enabled?
locking_column = self.class.locking_column
scope = scope.where(locking_column => _read_attribute(locking_column))
changes[locking_column] = increment_lock
end
result = scope.update_all(changes) == 1
if !result && locking_enabled?
raise ActiveRecord::StaleObjectError.new(self, "touch")
end
result
else
true
end
......
......@@ -177,6 +177,16 @@ def test_touch_existing_lock
assert_equal 1, p1.lock_version
end
def test_touch_stale_object
person = Person.create!(first_name: 'Mehmet Emin')
stale_person = Person.find(person.id)
person.update_attribute(:gender, 'M')
assert_raises(ActiveRecord::StaleObjectError) do
stale_person.touch
end
end
def test_lock_column_name_existing
t1 = LegacyThing.find(1)
t2 = LegacyThing.find(1)
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册