File tree Expand file tree Collapse file tree 2 files changed +25
-3
lines changed
Expand file tree Collapse file tree 2 files changed +25
-3
lines changed Original file line number Diff line number Diff 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
Original file line number Diff line number Diff 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 )
You can’t perform that action at this time.
0 commit comments