Skip to content

Instantly share code, notes, and snippets.

@tasdikrahman
Forked from danielfone/aasm_after_commit.rb
Created August 4, 2020 07:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tasdikrahman/07c185f15608ca0050cd6d27ed27b9d6 to your computer and use it in GitHub Desktop.
Save tasdikrahman/07c185f15608ca0050cd6d27ed27b9d6 to your computer and use it in GitHub Desktop.
AASM after_commit behaviour
# ruby 2.2.2
# activerecord 4.2.3
# aasm 4.2.0
require 'active_record'
require 'aasm'
# Setup a mock AR table
ActiveRecord::Migration.verbose = false
ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:")
ActiveRecord::Schema.define(:version => 1) do
create_table :orders do |t|
t.string :aasm_state
end
end
# Example record with scope
class Order < ActiveRecord::Base
include AASM
aasm do
state :draft, initial: true
state :placed
event :place, after_commit: :log_placed do
transitions from: :draft, to: :placed
end
end
def log_placed
logger.info "Order has been placed"
end
end
o = Order.create!
ActiveRecord::Base.logger = Logger.new(STDOUT)
#
# The behaviour under question starts here
#
Order.transaction do
o.place!
raise ActiveRecord::Rollback
end
o.reload
o.logger.info o.aasm_state
# DEBUG -- : (0.1ms) begin transaction
# DEBUG -- : (0.0ms) SAVEPOINT active_record_1
# DEBUG -- : SQL (0.1ms) UPDATE "orders" SET "aasm_state" = ? WHERE "orders"."id" = ? [["aasm_state", "placed"], ["id", 1]]
# DEBUG -- : (0.0ms) RELEASE SAVEPOINT active_record_1
# INFO -- : Order has been placed
# DEBUG -- : (0.0ms) rollback transaction
# DEBUG -- : Order Load (0.1ms) SELECT "orders".* FROM "orders" WHERE "orders"."id" = ? LIMIT 1 [["id", 1]]
# INFO -- : draft
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment