0

I would like to generate a model record after another model record has been created.

Basically I tweaked Devise create action in registrations controller but this is not perfect. I would like to encapsulate into a transaction in case something fails on the second model creation the first one is not created either/rollbacked.

But there seems to be a better method using callbacks inside the model rather than tweaking the controller.

some refs : Rails on create transaction, Rails: Exception in after_create stopping save and http://webonrails.com/2012/08/28/activerecord-after_commit-hook/

Though I am not even sure I get the concept.

What I understand is that if I use after_create :create_model_2_instance inside the first model file and it fails, then the creation of the record of this very model will fail also. It's a binary result for both models then .. ?

Where I am a bit confused is in the last reference provided http://webonrails.com/2012/08/28/activerecord-after_commit-hook/ author says :

"Most developers use ActiveRecord callbacks after_create/after_update/after_destroy to generate background job, expire cache, etc., but they don’t realize these callbacks are still wrapped in database transaction, they probably got unexpected results like the app queued a job but the record is not created/updated(transaction rolled back)."

So basically he enforces the fact that after_create is encapsulated in a transaction. So let's say I queue a background job that is triggered 3 hours after the record is created. If it fails the original record will be destroyed/rollbacked 3 hours after its creation ?

Maxence
  • 2,029
  • 4
  • 18
  • 37

1 Answers1

2

Yes, after_create is wrapped in a transaction in rails , so that all the transaction must be committed to database, if any one of the record is unable to save in the database then the whole transaction block is rolled back.

As a workaround , if you want each insertion to be a separate transaction , then you could use after_commit callback in which once the transaction has been comitted it can no longer be rolled back.

Rohan
  • 2,681
  • 1
  • 12
  • 18