2

我们有葡萄 API,但我想知道我们是否可以在每次请求时用活动记录事务包装它。

在进行交易的活动记录中,我们可以这样做:

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

如何将它包装到葡萄 API 中?

据我所知,在 Grape API 中,我们可以实现before方法和after方法。

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
4

1 回答 1

3

查看活动记录中块的实现transaction,您应该执行以下操作:

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
于 2014-05-06T05:52:35.290 回答