只有在事务未回滚时才执行不可逆操作
Do something only after the currently open transactions have finished.
Normally everything gets rolled back when a transaction fails, but you cannot roll back sending an email or adding a job to Resque.
gem install ar_after_transactionclass User
after_create :do_stuff, :oops
def do_stuff
after_transaction do
send_an_email # cannot be rolled back
end
comments.create(...) # will be rolled back
end
def oops
raise "do the rolback!"
end
endclass Resque
def revertable_enqueue(*args)
ActiveRecord::Base.after_transaction do
enqueue(*args)
end
end
endafter_transaction will perform the given block immediately
after_transaction assumes zero open transactions.
If you use transactional fixtures you should change it in test mode.
Rspec:
# spec/rails_helper.rb
config.before(:suite) do
ActiveRecord::Base.normally_open_transactions = 1
endar_after_transaction.gemspecBUNDLE_GEMFILE=gemfiles/.gemfile bundleBUNDLE_GEMFILE=gemfiles/.gemfile bundle exec rake.github/workflows/actions.ymlRails 3+
after_commit :fooafter_commit :bar, on: :create / :updatepro: threadsafe
pro: more fine-grained callbacks (before_commit, after_commit, before_rollback, after_rollback)
con: doesn't let you define after_transaction callbacks anywhere like ar_after_transaction does (outside of the after_commit, etc. callbacks which only happen at certain points in the model's life cycle)
con: more complex
Original idea and code from Jamis Buck (post by Jeremy Kemper)
License: MIT
暂无开放 Issues,或尚未同步最近议题。