Getting Started with Active Record Transactions

suggest change

Active Record transactions can be opened on a model class or an instance. The objects inside the block do not have to be instances of the same class. A transaction belongs to the database connection, not to one model. For example, in a controller:

begin
  User.transaction do
    account.save!
    profile.save!
    print "All saves succeeded, returning 1"
    return 1
  end
rescue ActiveRecord::RecordInvalid => exception
  print "Exception thrown, transaction rolled back"
  render_error "failure", exception.record.errors.full_messages.to_sentence
end

rescue_from is a controller class macro. It does not attach to a transaction block. Use rescue for that, or rescue_from at class level.

save! raises when validation fails, and the transaction rolls back. Rescue that exception after the rollback. A bare return inside the block still commits, because it does not raise.

If you don’t want to use save!, raise ActiveRecord::Rollback when the save fails. Rails does not re-raise that exception. The transaction rolls back and execution continues after the block.

User.transaction do
  if account.save && profile.save
    print "All saves succeeded, returning 1"
    return 1
  else
    raise ActiveRecord::Rollback
  end
end
print "Transaction rolled back"

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents