使用 ActiveRecord 冒泡嵌套事务失败

编程入门 行业动态 更新时间:2024-10-20 21:06:45
本文介绍了使用 ActiveRecord 冒泡嵌套事务失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在服务对象中有一个方法,该方法组合应包含在事务中的操作.其中一些操作也包含在事务中.例如:

I have a method in a service object that composes operations that should be wrapped in a transaction. Some of these operations are also wrapped in transactions. For example:

class PostCreator def create ActiveRecord::Base.transaction do post.do_this post.do_that user.do_more(post, other_stuff) end end end def Post def do_this transaction do; ...; end end end

我需要任何嵌套失败一直冒泡到顶部,但我不知道如何实现这一点,以及 嵌套事务 似乎没有提供解决方案.来自文档:

I need any nested failures to bubble up all the way to the top, but I'm not sure how to make that happen, and the ActiveRecord docs on nested transactions don't seem to offer a solution. From the docs:

# Standard nesting User.transaction do User.create(username: 'Kotori') User.transaction do User.create(username: 'Nemu') raise ActiveRecord::Rollback # This won't bubble up: # _Both_ users will still be created. end end # Nesting with `requires_new: true` on the nested transaction User.transaction do User.create(username: 'Kotori') User.transaction(requires_new: true) do User.create(username: 'Nemu') raise ActiveRecord::Rollback # This won't bubble up either # "Kotori" will still be created. end end

推荐答案

以下是使嵌套事务中的失败冒泡的方法:

Here's how you could get failures in your nested transactions to bubble up:

User.transaction do User.create(username: 'Kotori') raise ActiveRecord::Rollback unless User.transaction(requires_new: true) do User.create(username: 'Nemu') raise ActiveRecord::Rollback end end

基本上,您必须在顶级事务中引发错误才能使其回滚.为此,如果嵌套事务返回假值(nil)或真值,则会引发错误.

Basically, you have to raise an error in your top-level transaction for it to rollback too. To do that, you raise an error if the nested transaction returns a falsey value(nil) or a truthy value.

希望有帮助!

更多推荐

使用 ActiveRecord 冒泡嵌套事务失败

本文发布于:2023-10-25 13:53:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1527142.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   事务   ActiveRecord

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!