4.13. Transactions

In the world of databases, the term transaction refers to a block of SQL statements that must be executed together and without interruption. If an error should occur within the transaction, the database is reset to the state before the start of the transaction.
Now and again, there are areas of application where you need to carry out a database transaction. The classic example is transferring money from one account to another. That only makes sense if both actions (debiting one account and crediting the recipient's account) are executed.
A transaction follows this pattern:
ActiveRecord::Base.transaction do
  Book.create(:title => 'A')
  Book.create(:title => 'B')
  Book.create(:title => 'C').authors.create(:last_name => 'Z')
Transactions are a complex topic. If you want to find out more, you can consult the ri help on the shell via ri ActiveRecord::Transactions::ClassMethods.


The methods save and destroy are automatically executed within the transaction wrapper. That way, Rails ensures that no undefined state can arise for these two methods.


Transactions are not natively supported by all databases. In that case, the code will still work, but you no longer have the security of the transaction.

Updates about this book will be published on my Twitter feed.