Use Transactions

This guide shows you how to use database transactions to ensure multiple operations succeed or fail together.

Basic Transaction

Wrap operations in a transaction block:

User.transaction do
  user = User.create!(name: "John", email: "john@example.com")
  Profile.create!(user_id: user.id.not_nil!, bio: "Hello")
end
# Both records created, or neither

Automatic Rollback on Error

If any operation fails, all changes are rolled back:

User.transaction do
  user = User.create!(name: "John", email: "john@example.com")
  raise "Something went wrong!"  # Triggers rollback
  Profile.create!(user_id: user.id.not_nil!, bio: "Hello")
end
# Neither record is created

Handle Transaction Errors

Transfer Between Records

Classic use case - moving money between accounts:

Nested Operations

All nested operations are part of the same transaction:

Manual Rollback

Raise an exception to trigger rollback:

Transaction with Return Value

Return a value from the transaction:

Cleanup Operations

Ensure cleanup happens even on failure:

Verify Transaction Behavior

Last updated

Was this helpful?