Search code examples
ruby-on-railsrubyactiverecordtransactionsgrape-api

Grape API + Active Record Wrapping Transaction


We have grape API but I wonder if we can wrap it with active record transaction every time we do request.

In active record to do transaction, we can do something like this:

 ActiveRecord::Base.transaction do
    # do select
    # do update
    # do insert
 end

How can I wrap it into grape API?

As far as i know, in Grape API we can implement before method and after method.

class API < Grape::API
   before do
     # ????? Need to implement code here to begin active record transaction
     # this suppose to begin active record transaction
   end
   after do
     # ????? Need to implement code here to end active record transaction
     # this suppose to end active record transaction
   end
end

Solution

  • Looking at the implementation of transaction block in active record, you should do something like:

    class API < Grape::API
    
      before do
        ActiveRecord::Base.connection.begin_transaction
      end
    
      after do
        begin
          ActiveRecord::Base.connection.commit_transaction unless @error
        rescue Exception
          ActiveRecord::Base.connection.rollback_transaction
          raise
        end
      end
    
      rescue_from :all do |e|
        @error = e
        ActiveRecord::Base.connection.rollback_transaction
        # handle exception...
      end
    
    end