开发者

Ruby on Rails: how do I catch ActiveRecord::Rollback?

In my controller, I have code that looks like the following:

    @mymodel.transaction do 
      for a in arr
        @mymodel.some_method(a)
      end
    end

in @mymodel#some_method I could throw an ActiveRecord::Rollback exception which in the db does what it needs to do, however I then simply get an HTTP 500 and no way to catch the exception to let the user know i开发者_高级运维n an elegant way what went wrong.

I've tried wrapping @mymodel.transaction do in a begin/rescue block, but that won't do it either. What's the best way to catch the exception so I can present the proper view to the user?


From the ActiveRecord::Base documentation:

Normally, raising an exception will cause the transaction method to rollback the database transaction and pass on the exception. But if you raise an ActiveRecord::Rollback exception, then the database transaction will be rolled back, without passing on the exception.

A small example:

class ThrowController < ApplicationController
  def index
      status = ActiveRecord::Base.connection.transaction do
        raise ActiveRecord::Rollback.new
      end

      Rails.logger.info "followed transaction"
  end
end

then:

>> c = ThrowController.new.index
=> "followed transaction \n"

As you can see, the ActiveRecord:::Rollback exception is swallowed by the transaction block.

It seems to me that something else is going on with your code that we're not aware of.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜