如何判断Rails 3事务是否成功通过?

时间:2012-08-17 19:57:49

标签: ruby-on-rails activerecord

有没有办法确定我的事务是否成功提交(并且没有回滚)?

Inventory.transaction do
  beads.each do |bead|
    # update something
    # insert something
    # delete something
  end
end

或者这样的事情是唯一的方法吗?

success = false
Inventory.transaction do
  beads.each do |bead|
    # update something
    # insert something
    # delete something
  end
  success = true
end

if success
  # do something
end

或者,因为异常被传播,如果没有异常就假设成功?

1 个答案:

答案 0 :(得分:0)

如果您担心异常,为什么不将它包装在try / catch块(或begin / rescue块中,以更加Rubyish)?

begin
  Inventory.transaction do
    beads.each do |bead|
      # update something
      # insert something
      # delete something
    end
  end
rescue WhateverError
  #handle error
end