Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails on create transaction

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
like image 359
soliman Avatar asked Oct 31 '22 01:10

soliman


1 Answers

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.

like image 51
nesiseka Avatar answered Nov 15 '22 06:11

nesiseka