1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Merge pull request #39321 from kamipo/fix_update_with_dirty_locking_column

Fix update with dirty locking column to not match latest object accidentally
This commit is contained in:
Ryuta Kamizono 2020-05-18 11:46:04 +09:00 committed by GitHub
commit a095916df1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 33 additions and 10 deletions

View file

@ -132,14 +132,13 @@ module ActiveModel
coder["value"] = value if defined?(@value) coder["value"] = value if defined?(@value)
end end
protected def original_value_for_database
def original_value_for_database if assigned?
if assigned? original_attribute.original_value_for_database
original_attribute.original_value_for_database else
else _original_value_for_database
_original_value_for_database
end
end end
end
private private
attr_reader :original_attribute attr_reader :original_attribute
@ -167,6 +166,7 @@ module ActiveModel
def _original_value_for_database def _original_value_for_database
value_before_type_cast value_before_type_cast
end end
private :_original_value_for_database
end end
class FromUser < Attribute # :nodoc: class FromUser < Attribute # :nodoc:

View file

@ -88,7 +88,7 @@ module ActiveRecord
affected_rows = self.class._update_record( affected_rows = self.class._update_record(
attributes_with_values(attribute_names), attributes_with_values(attribute_names),
@primary_key => id_in_database, @primary_key => id_in_database,
locking_column => previous_lock_value locking_column => @attributes[locking_column].original_value_for_database
) )
if affected_rows != 1 if affected_rows != 1

View file

@ -238,14 +238,37 @@ class OptimisticLockingTest < ActiveRecord::TestCase
end end
end end
def test_update_with_dirty_locking_column
person = Person.find(1)
person.first_name = "Douglas Adams"
person.lock_version = 42
changes = {
"first_name" => ["Michael", "Douglas Adams"],
"lock_version" => [0, 42],
}
assert_equal changes, person.changes
assert person.save!
assert_empty person.changes
end
def test_explicit_update_lock_column_raise_error def test_explicit_update_lock_column_raise_error
person = Person.find(1) person = Person.find(1)
person2 = Person.find(1)
person2.lock_version = 42
person2.save!
assert_raises(ActiveRecord::StaleObjectError) do assert_raises(ActiveRecord::StaleObjectError) do
person.first_name = "Douglas Adams" person.first_name = "Douglas Adams"
person.lock_version = 42 person.lock_version = person2.lock_version
assert_predicate person, :lock_version_changed? changes = {
"first_name" => ["Michael", "Douglas Adams"],
"lock_version" => [0, 43],
}
assert_equal changes, person.changes
person.save person.save
end end