Skip to content

Instantly share code, notes, and snippets.

@gilr00y
Last active August 29, 2015 14:02
Show Gist options
  • Save gilr00y/70f2d0ac43049cba059f to your computer and use it in GitHub Desktop.
Save gilr00y/70f2d0ac43049cba059f to your computer and use it in GitHub Desktop.
ActiveRecord Cross-DB transactions
# AR transactions wrap a block of code, issuing a rollback if any errors are raised.
#
#(note: this gist makes use of SecondBase https://github.com/customink/secondbase)
require 'secondbase/model'
AR = ActiveRecord::Base
SB = SecondBase::Base
# The transaction returns the return value of the block
AR.transaction { 14 } #=> 14
# Errors are propagated...
AR.transaction { raise } #=> RuntimeError
# ...except ActiveRecord::Rollback errors
AR.transaction { raise ActiveRecord::Rollback } #=> nil
# --
# What does this mean cross-db??
# --
# We can nest transactions...
AR.transaction do
SB.transaction do
14
end
end #=> 14
# ...as long as we mind our errors!
AR.transaction do
SB.transaction do
ARModel.save
if SBModel.new.save
raise ActiveRecord::RecordNotSaved #=> Error will be propagated, and both AR and SB rollbacks issues
end
end
end
AR.transaction do
SB.transaction do
ARModel.save
if !SBModel.new.save
raise ActiveRecord::Rollback #=> Error will NOT be propagated, only SB rollback issued
end
end #=> nil
end #=> nil, even though the AR record has been saved!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment