Last Updated: May 06, 2016
·
1.101K
· yanhaoyang

Wrap multiple requests in one transaction

If a Rails server is running in single threading mode, you can begin a transaction by a request, then end a transaction with another request. All requests between these two requests will be wrapped in one transaction. How can this be useful? Sometimes.

module Concerns
  module Transactions
    extend ActiveSupport::Concern

    def transaction_begin
      ActiveRecord::Base.connection.begin_db_transaction
      ActiveRecord::Base.connection.increment_open_transactions
      render nothing: true
    end

    def transaction_rollback
      ActiveRecord::Base.connection.decrement_open_transactions
      ActiveRecord::Base.connection.rollback_db_transaction
      render nothing: true
    end

  end
end

1 Response
Add your response

Is this still relevant?

I was thinking about having test-transaction-like functionality in development mode;

Like – submit a form, see what happens, and rollback by clicking some button.

over 1 year ago ·