transaction(requires_new: nil, isolation: nil, joinable: true, &block) public

Runs the given block in a database transaction, and returns the result of the block.

Nested transactions support

#transaction calls can be nested. By default, this makes all database statements in the nested transaction block become part of the parent transaction. For example, the following behavior may be surprising:

ActiveRecord::Base.transaction do
  Post.create(title: 'first')
  ActiveRecord::Base.transaction do
    Post.create(title: 'second')
    raise ActiveRecord::Rollback
  end
end

This creates both “first” and “second” posts. Reason is the ActiveRecord::Rollback exception in the nested block does not issue a ROLLBACK. Since these exceptions are captured in transaction blocks, the parent block does not see it and the real transaction is committed.

Most databases don’t support true nested transactions. At the time of writing, the only database that supports true nested transactions that we’re aware of, is MS-SQL.

In order to get around this problem, #transaction will emulate the effect of nested transactions, by using savepoints: dev.mysql.com/doc/refman/en/savepoint.html.

It is safe to call this method if a database transaction is already open, i.e. if #transaction is called within another #transaction block. In case of a nested call, #transaction will behave as follows:

  • The block will be run without doing anything. All database statements that happen within the block are effectively appended to the already open database transaction.

  • However, if :requires_new is set, the block will be wrapped in a database savepoint acting as a sub-transaction.

In order to get a ROLLBACK for the nested transaction you may ask for a real sub-transaction by passing requires_new: true. If anything goes wrong, the database rolls back to the beginning of the sub-transaction without rolling back the parent transaction. If we add it to the previous example:

ActiveRecord::Base.transaction do
  Post.create(title: 'first')
  ActiveRecord::Base.transaction(requires_new: true) do
    Post.create(title: 'second')
    raise ActiveRecord::Rollback
  end
end

only post with title “first” is created.

See ActiveRecord::Transactions to learn more.

Caveats

MySQL doesn’t support DDL transactions. If you perform a DDL operation, then any created savepoints will be automatically released. For example, if you’ve created a savepoint, then you execute a CREATE TABLE statement, then the savepoint that was created will be automatically released.

This means that, on MySQL, you shouldn’t execute DDL operations inside a #transaction call that you know might create a savepoint. Otherwise, #transaction will raise exceptions when it tries to release the already-automatically-released savepoints:

Model.connection.transaction do  # BEGIN
  Model.connection.transaction(requires_new: true) do  # CREATE SAVEPOINT active_record_1
    Model.connection.create_table(...)
    # active_record_1 now automatically released
  end  # RELEASE SAVEPOINT active_record_1  <--- BOOM! database error!
end

Transaction isolation

If your database supports setting the isolation level for a transaction, you can set it like so:

Post.transaction(isolation: :serializable) do
  # ...
end

Valid isolation levels are:

  • :read_uncommitted

  • :read_committed

  • :repeatable_read

  • :serializable

You should consult the documentation for your database to understand the semantics of these different levels:

  • www.postgresql.org/docs/current/static/transaction-iso.html

  • dev.mysql.com/doc/refman/en/set-transaction.html

An ActiveRecord::TransactionIsolationError will be raised if:

  • The adapter does not support setting the isolation level

  • You are joining an existing open transaction

  • You are creating a nested (savepoint) transaction

The mysql2 and postgresql adapters support setting the transaction isolation level.

Show source
Register or log in to add new notes.
September 11, 2008 - (<= v2.1.0)
4 thanks

Information on 'ModelName.transaction'

If you are looking for information about:

ModelName.transaction do
  ...
end

or

transaction do
  ...
end

see ActiveRecord::Transactions::ClassMethods

January 3, 2011
1 thank

Rollback

To rollback the transaction

transaction do
  unless user.save && company.save
     raise raise ActiveRecord::Rollback
  end
end

Or - catch anonymous exceptions, roll back and re-throw error

transaction do
  user.save
  company.save
  x = 1/0
rescue
  exp = $!
  begin
    raise ActiveRecord::Rollback
  rescue
  end
  raise exp
end