首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检查多插入事务是否成功。

检查多插入事务是否成功。
EN

Stack Overflow用户
提问于 2013-10-30 18:10:42
回答 1查看 6.1K关注 0票数 4

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

代码语言:javascript
复制
    ...

      # 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

    ...
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-10-30 18:19:12

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

代码语言:javascript
复制
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,因为如果出错,它将引发错误。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19690687

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档