💎 Ruby on Rails
Intermediate
What are transactions in ActiveRecord?
Answer
ActiveRecord transactions wrap a block of database operations in a single atomic unit — either all succeed or all are rolled back on error. Syntax: ActiveRecord::Base.transaction do ... end or User.transaction do ... end. If an exception is raised inside the block, the transaction is rolled back. Use raise ActiveRecord::Rollback to manually roll back without propagating an exception. Important: only database exceptions trigger automatic rollback — always raise ActiveRecord::Rollback explicitly for business logic failures. Transactions are critical for operations that must be atomic, like transferring funds.