Skip to content

Instantly share code, notes, and snippets.

@DanThiffault
Created February 16, 2016 22:37
Show Gist options
  • Save DanThiffault/1cad32c64fc026e3d4d1 to your computer and use it in GitHub Desktop.
Save DanThiffault/1cad32c64fc026e3d4d1 to your computer and use it in GitHub Desktop.
Rails nested transactions

See Nested Transactions for more information.

TL;DR if you're going to use nested transactions you probably should not raise ActiveRecord::Rollback

def test_user(step)
AdminUser.where(email: "sad.trombone#{step}@rails.org")
end
[ActiveRecord::Rollback, RuntimeError].each do |my_error|
puts "Testing with #{my_error.to_s}"
puts 'Deleting test users if they exists'
test_user(1).delete_all
test_user(2).delete_all
puts 'sad.trombone 1 exists? ' + test_user(1).exists?.to_s
puts 'sad.trombone 2 exists? ' + test_user(2).exists?.to_s
puts 'About to enter transaction block'
begin
AdminUser.transaction do
AdminUser.create!(email: '[email protected]', password: 'password')
AdminUser.transaction do
AdminUser.create!(email: '[email protected]', password: 'password')
raise my_error
end
end
rescue
end
puts 'Done with transactions'
puts 'sad.trombone 1 exists? ' + test_user(1).exists?.to_s
puts 'sad.trombone 2 exists? ' + test_user(2).exists?.to_s
end
Testing with ActiveRecord::Rollback
Deleting test users if they exists
sad.trombone 1 exists? false
sad.trombone 2 exists? false
About to enter transaction block
Done with transactions
sad.trombone 1 exists? true
sad.trombone 2 exists? true
Testing with RuntimeError
Deleting test users if they exists
sad.trombone 1 exists? false
sad.trombone 2 exists? false
About to enter transaction block
Done with transactions
sad.trombone 1 exists? false
sad.trombone 2 exists? false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment