6.7.2. Using Transactions

Transactions are the standard relational database mechanism for maintaining data integrity when several database operations are related to each other. The basic idea is that you explicitly enter a transaction block, and then any error that occurs while actions are performed inside the block automatically causes the database to roll back to its pre-transaction state. The canonical example is a bank transfer, where you want both the withdrawal and the deposit to occur together, or not at all.

Rails automatically places both save and destroy calls inside a transaction so that any associated objects are saved or destroyed within the transaction block. This covers the most common use of transactions; however, you'll still need to use them manually from time to time. The transaction method is invoked as a class method of ActiveRecord, like this:

begin
  Recipe.transaction do
    recipe1.save
    recipe2.save
  end
rescue Exception => e
  return false
end

You need the begin/rescue/end block if you want to handle any exception thrown in the transaction block. Rails will propagate the exception.

The important thing to note here is that any change you make to the ActiveRecord objects in memory inside the transaction block will still hold even if the transaction rolls back the database. (There used to be a mechanism to include the ActiveRecord objects in the transaction as well, but it was deprecated in the Rails 1.2 timeframe.)

The other notable limitation is that a transaction ...

Get Professional Ruby on Rails™ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.