3

我有一种情况,我需要在成功创建 'foo' 之后执行 'do_this',并且在没有错误地执行 'do_this' 时执行 'do_that',如下所示:

class Foo < ActiveRecord::Base

  around_create do |foo, block|
    transaction do
      block.call # invokes foo.save

      do_this!
      do_that!
    end
  end

  protected

  def do_this!
    raise ActiveRecord::Rollback if something_fails
  end

  def do_that!
    raise ActiveRecord::Rollback if something_else_fails
  end

end

并且应该回滚整个事务,以防其中一个失败。

然而问题是,即使 'do_this' 或 'do_that' 失败, 'foo' 也会一直存在。是什么赋予了?

4

1 回答 1

4

您不需要这样做,如果您将 false 返回到回调,它将触发回滚。编写您想要的代码的最简单方法是这样的

after_save :do_this_and_that

def do_this_and_that
  do_this && do_that
end

def do_this
  # just return false here if something fails. this way,
  # it will trigger a rollback since do_this && do_that
  # will be evaluated to false and do_that will not be called
end

def do_that
  # also return false here if something fails to trigger
  # a rollback
end
于 2013-02-19T13:59:51.287 回答