I'm using ActiveMerchant to process a credit card transaction which may succeed or fail, which is part of a bigger transaction involving some internal accounting using ActiveRecord processing. I am not clear on how to roll back the entire transaction if a part fails.
I have a Payment model, and a Points model -- a user's points are converted to dollars to be used to reduce their payment. So I need to do these things:
- Several validations relating to amount and points
- Save points transactions: Debit user account, credit internal account
- Charge credit card the amount of payment less value from points
- Save this payment data
- Save the credit card transaction result (whether it succeeds or fails)
- Then if everything works, send an email to the user
I see how ActiveRecord::Transactions work, and assume I can use the after_commit
(and after_rollback
) callbacks to handle stuff like emailing the user.
But how do I make a failed credit card transaction cause the same rollback that a failed AR save
would cause? Is it as easy as calling raise ActiveRecord::Rollback
if my non-AR transaction fails? There's a section in the doc linked above that makes me nervous about this (relating to transactions not working across multiple database connections).
Rails 3.2.5, MySQL 5.1 (InnoDB), Ruby 1.9.3
ActiveRecord::Rollback
. – Tanzeeb Khalili