ruby-on-rails – 用ActiveRecord冒泡嵌套事务失败
发布时间:2020-12-16 20:35:27 所属栏目:百科 来源:网络整理
导读:我在服务对象中有一个方法,该方法组合应该包含在事务中的操作.其中一些操作也包裹在事务中.例如: 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
我在服务对象中有一个方法,该方法组合应该包含在事务中的操作.其中一些操作也包裹在事务中.例如:
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 我需要任何嵌套的失败来一直到顶部,但我不知道如何发生这种情况,而在nested transactions的ActiveRecord文档似乎没有提供一个解决方案.从文档: # 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 解决方法
以下是您可以在嵌套交易中获得失败的原因:
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)或一个真值,你会引发一个错误. 希望有帮助! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |