Ruby-on-rails ActiveRecord 事务中的错误处理?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1937795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:03:38  来源:igfitidea点击:

Error Handling in ActiveRecord Transactions?

ruby-on-railsactiverecord

提问by Kevin

I need to create a row in both tickets and users table... I just need to know how to process in case the transaction fails.

我需要在票证和用户表中创建一行......我只需要知道如何处理,以防交易失败。

@ticket.transaction do
    @ticket.save!
    @user.save!
end
    #if (transaction succeeded)
        #.....
    #else (transaction failed)
        #......
    #end

On a side note I'd just like to thank everyone who participates at stack overflow for helping a designer learn more programming... I appreciate the time you guys take out of your day to answer n00b questions like this :)

在旁注中,我只想感谢参与堆栈溢出的每个人帮助设计师学习更多编程......我感谢你们抽出时间来回答这样的 n00b 问题:)

回答by MattMcKnight

If you are using the save! method with a bang (exclamation point), the application will throw an exception when the save fails. You would then have to catch the exception to handle the failure.

如果您使用的是保存!方法带有 bang(感叹号),应用程序将在保存失败时抛出异常。然后,您必须捕获异常以处理失败。

begin
  @ticket.transaction do
    @ticket.save!
    @user.save!
  end
  #handle success here
rescue ActiveRecord::RecordInvalid => invalid
   #handle failure here
end

回答by mportiz08

i'm also a beginner, but i believe that you can check @ticket.errors and @user.errors and validate according to their responses

我也是初学者,但我相信你可以检查@ticket.errors 和@user.errors 并根据他们的回应进行验证

also the save method should return a boolean that determines if the save was successful

保存方法也应该返回一个布尔值来确定保存是否成功