Rails创建交易 [英] Rails on create transaction

查看:69
本文介绍了Rails创建交易的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在创建新用户时(在我的用户模型中),我也想创建一个条纹客户。这两个动作只有一起成功才能完成(例如,我不希望客户没有用户,反之亦然)。因此,我认为将它们包装在事务中是个好主意。但是,我一定不能正确地做它。我认为我无法正确覆盖create方法。如果有人有更好的建议,或者我做错了,将不胜感激。

On creating a new user (in my user model) i want to create a stripe customer as well. The two actions must only be completed if they succeed together (like i don't want a customer without a user and vice versa). For this reason I figured it would be a good idea to wrap them in a transaction. However, I must not be doing it correctly. I do not believe I am properly overwriting the create method. If anyone has a suggestion as a better way to do this or what I am doing wrong it would be much appreciated. Thanks!

  def create
    User.transaction do
      super
      create_stripe_customer(self)
    end
  end

  def destroy
    User.transaction do
      super
      delete_stripe_customer(self)
    end
  end


推荐答案

我已经对您的问题进行了一些研究并使用只要引发异常,after_create看起来就可以。这也将回滚事务。只需使用默认的回调即可。

I've done some research into your question and using after_create seems to be ok as long as an exception is raised if it fails. That will rollback the transaction as well. Just use the default callbacks.

这是一个与问题相关的好答案

这篇关于Rails创建交易的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆