Is it possible to re-raise an ActiveRecord::Rollback exception from inside a transaction block?

僤鯓⒐⒋嵵緔 提交于 2019-12-25 02:19:18

问题


In my rails app, I have a transaction block in a controller's create action in which I attempt to create two records.

def create
  ActiveRecord::Base.transaction do
    @foo = Foo.new(params[:foo].except(:bar))
    raise ActiveRecord::Rollback unless @foo.save
    @bar = Bar.new(params[:foo][:bar])
    raise ActiveRecord::Rollback unless @bar.save
  end
end

I'd like to be able to rescue from the Rollback so I can return an error indicating which save failed.

rescue ActiveRecord::Rollback => e
  @foo.errors = e if @foo.errors.blank?
ensure
  respond_with @foo
end

However, I never get into the rescue block. I assume this is because, as the rails documentation states, the transaction block eats the Rollback exception and doesn't re-raise it. Is there a way to force this exception to be re-raised?

来源:https://stackoverflow.com/questions/13656587/is-it-possible-to-re-raise-an-activerecordrollback-exception-from-inside-a-tra

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!