Skip to content

Instantly share code, notes, and snippets.

@rickharris
Created May 2, 2012 18:15
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 rickharris/2578872 to your computer and use it in GitHub Desktop.
Save rickharris/2578872 to your computer and use it in GitHub Desktop.
How do you do this??
# So, we want to wrap a block of code in a transaction, and if the transaction
# fails, we'd like to take another action that also uses the database. But how?
# Example #1 - Not possible
success = false
ActiveRecord::Base.transaction do
success = some_method
if success
# do something that gets rolled back
else
# do something that doesn't get rolled back
end
end
# Example #2 - Not reliable
success = false
ActiveRecord::Base.transaction do
# Say this succeeds
success = some_other_crazy_db_operation
# But this throws an error, causing a rollback
some_crazy_db_operation
end
if !success
# This does not get executed, even though the rollback occured,
# because `success` evaluated to true before the rollback was raised
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment