Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Raise StaleObjectError if touched object is stale and locking is enabled #19783

Merged
merged 1 commit into from
Apr 19, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 15 additions & 3 deletions activerecord/lib/active_record/persistence.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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?
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about

scope = self.class.unscoped.where(primary_key => self[primary_key])

if locking_enabled?
  lock_column = self.class.locking_column
  lock_val = self[lock_column]
  scope = scope.where(lock_column => lock_val)

  if scope = scope.update_all(changes) != 1
    raise ActiveRecord::StaleObjectError.new(self, "touch")
  end

  true
else
  scope_update_all(changes) == 1
end

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?
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Put a blank line before the if and after the end

raise ActiveRecord::StaleObjectError.new(self, "touch")
end

result
else
true
end
Expand Down
10 changes: 10 additions & 0 deletions activerecord/test/cases/locking_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down