5

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
soliman
  • 105
  • 11
  • 1
    I generally use transaction blocks as a critical section with database lock to prevent race condition. In your case, will there be any problem if you call `create_stripe_customer` in your `after_create` callback on User model ? If create_stripe_customer fails then your User creation should be rolled back as well. – Vijay Meena Jun 21 '15 at 05:21
  • I am following. somebody must be having a good answer to this question. – Vijay Meena Jun 21 '15 at 05:22
  • will failure of the after_creation method cause a rollback? if so that is perfect and would solve my issue. I had that initially, but was unsure if failure caused a rollback or not. – soliman Jun 21 '15 at 05:41

1 Answers1

2

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.

Community
  • 1
  • 1
nesiseka
  • 1,268
  • 8
  • 22
  • Thank you. I looked into that as well after Vijay's suggestion above and it seems to perform the needed results. Thank you both for your help! – soliman Jun 21 '15 at 17:14