Rails on create transaction

2019-06-22 08:21发布

问题:

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

回答1:

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.

Here is a good answer related to the question.