From 210729c4cc05eae875b1e990c5bce39dee23e8f1 Mon Sep 17 00:00:00 2001 From: Vipul A M Date: Sun, 24 Apr 2016 04:01:18 +0530 Subject: [PATCH] Followup of #15771 Make sure we handle explicitly passed nil's to lock_version as well. An explicitly passed nil value is now converted to 0 on LockingType, so that we don't end up with ActiveRecord::StaleObjectError in update record optimistic locking Fixes #24695 --- activerecord/lib/active_record/locking/optimistic.rb | 4 ++++ activerecord/test/cases/locking_test.rb | 6 ++++++ 2 files changed, 10 insertions(+) diff --git a/activerecord/lib/active_record/locking/optimistic.rb b/activerecord/lib/active_record/locking/optimistic.rb index 2336d23a1c..1040327a5d 100644 --- a/activerecord/lib/active_record/locking/optimistic.rb +++ b/activerecord/lib/active_record/locking/optimistic.rb @@ -190,6 +190,10 @@ module ActiveRecord super.to_i end + def serialize(value) + super.to_i + end + def init_with(coder) __setobj__(coder['subtype']) end diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb index 6c59d7337a..9fc0041892 100644 --- a/activerecord/test/cases/locking_test.rb +++ b/activerecord/test/cases/locking_test.rb @@ -169,6 +169,12 @@ class OptimisticLockingTest < ActiveRecord::TestCase assert_equal 1, p1.lock_version end + def test_lock_new_when_explicitly_passing_nil + p1 = Person.new(:first_name => 'anika', lock_version: nil) + p1.save! + assert_equal 0, p1.lock_version + end + def test_touch_existing_lock p1 = Person.find(1) assert_equal 0, p1.lock_version