Skip to content

Instantly share code, notes, and snippets.

@iiwo
Created March 15, 2019 15:22
Show Gist options
  • Save iiwo/2708adb60de50d539d6736ee7a1ead3e to your computer and use it in GitHub Desktop.
Save iiwo/2708adb60de50d539d6736ee7a1ead3e to your computer and use it in GitHub Desktop.
after_commit.rb
# frozen_string_literal: true
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
# Activate the gem you are reporting the issue against.
gem "activerecord", "5.2.0"
gem "sqlite3", "~> 1.3.6"
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 :accounts, force: true do |t|
t.string :first
t.string :second
end
end
class Account < ActiveRecord::Base
after_commit :handle_after_commit, on: :update
def handle_after_commit
puts "after_commit: changes: #{previous_changes}"
end
end
account_1 = Account.create!
account_2 = Account.create!
ActiveRecord::Base.transaction do
account_1.update!(first: 'updating first on 1')
account_1.update!(second: 'updating second on 1')
account_2.update!(first: 'updating first on 2')
account_2.update!(second: 'updating second on 2')
end
# result:
# after_commit: changes: {"second"=>[nil, "updating second on 1"]}
# after_commit: changes: {"second"=>[nil, "updating second on 2"]}
#
# after_commit is triggered once at the end of transaction block
# be careful when using previous_changes inside of a transaction
# and when discrate operations matter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment