检查多插入事务是否成功

时间:2013-10-30 18:10:43

标签: ruby-on-rails activerecord transactions ruby-on-rails-4

我需要在提交表单后进行一些处理,最终会在多个表中保存多个记录。因为我需要它是全有或全无,我把它包装在一个事务块中。该块似乎工作正常,但我不知道如何检查交易是否成功,所以我可以返回适当的响应。

    ...

      # Start a transaction block so we can back out if anything fails
      ActiveRecord::Base.transaction do

        # Journal Entry for from_account
        gle = from_account.gl_journal_entries.create(....)

        # Journal Line (x2)
        gle.gl_journal_lines.create(....)
        gle.gl_journal_lines.create(....)


        # Journal Entry for to_account
        gle = to_account.gl_journal_entries.create(....)

        # Journal Line (x2)
        gle.gl_journal_lines.create(....)
        gle.gl_journal_lines.create(....)

      end

      # return something based on success/failure of transaction

    ...

1 个答案:

答案 0 :(得分:3)

一种选择是捕捉它可能会或可能不会抛出的错误。在这种情况下:

def my_method

  ...

  ActiveRecord::Base.transaction do
    # Journal Entry for from_account
    gle = from_account.gl_journal_entries.create!(....)

    # Journal Line (x2)
    gle.gl_journal_lines.create!(....)
    gle.gl_journal_lines.create!(....)


    # Journal Entry for to_account
    gle = to_account.gl_journal_entries.create!(....)

    # Journal Line (x2)
    gle.gl_journal_lines.create!(....)
    gle.gl_journal_lines.create!(....)
  end

  # this code will only get executed if the transaction succeeds

rescue Exception => ex

  # this code will only get executed if the transaction fails

end

编辑:在此实例中建议使用create!而不是create,因为如果出现任何问题,它会抛出错误。