Skip to content

after_commit doesn't work with optimistic locking #29318

@morganatwishpond

Description

@morganatwishpond

Steps to reproduce

begin
  require "bundler/inline"
rescue LoadError => e
  $stderr.puts "Bundler version 1.10 or later is required. Please update your Bundler"
  raise e
end

gemfile(true) do
  source "https://rubygems.org"
  gem "rails", github: "rails/rails"
  gem "arel", github: "rails/arel"
  gem "sqlite3"
end

require "active_record"
require "minitest/autorun"
require "logger"

# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Base.logger = Logger.new(STDOUT)

ActiveRecord::Schema.define do
  create_table :people do |t|
    t.string :name
    t.integer :lock_version, null: false, default: 0
    t.timestamps
  end

  create_table :places do |t|
    t.string :name
    t.timestamps
  end
end

$with_optimistic_locking = []
$without_optimistic_locking = []

class Person < ActiveRecord::Base
  after_update do
    $with_optimistic_locking << 'after_update'
  end

  after_commit on: :update do
    $with_optimistic_locking << 'after_commit on: :update'
  end
end

class Place < ActiveRecord::Base
  after_update do
    $without_optimistic_locking << 'after_update'
  end

  after_commit on: :update do
    $without_optimistic_locking << 'after_commit on: :update'
  end
end

class BugTest < Minitest::Test

  def test_update_and_commit_with_optimistic_locking
    place = Person.new(name: 'Paris')
    place.save

    place.name = 'Georgia'
    place.save
    
    assert_equal [
      'after_update',
      'after_commit on: :update'
    ], $with_optimistic_locking
  end

  def test_update_and_commit_without_optimistic_locking
    place = Place.new(name: 'Adelaide')
    place.save

    place.name = 'Alberta'
    place.save

    assert_equal [
      'after_update',
      'after_commit on: :update'
    ], $without_optimistic_locking
  end

end

Expected behavior

after_commit on: :update callbacks should fire even when optimistic locking is in use.

Actual behavior

after_commit on: :update callbacks do not fire when optimistic locking is enabled.

System configuration

Rails version: 5.1.1

Ruby version: 2.4.1

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions