transaction(options = {}) public

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

Nested transactions support

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: http://dev.mysql.com/doc/refman/5.0/en/savepoints.html Savepoints are supported by MySQL and PostgreSQL, but not SQLite3.

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.

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
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