Rails: Exception in after_create stopping save
Asked Answered
L

1

22

Simple question. I have a ActiveRecord model that I want to perform post processing on AFTER the record is saved. So in the model I have a queue_for_processing method that sticks a job onto my Resque queue. To make this execute after my record is successfully persisted I have written the following in my model:

after_create :queue_for_processing

Pretty simple. I had thought that everything was working as expected EXCEPT that last night my redis server went down and things went awry. My expectations were that the record would still be saved and I could process the job later manually. But the queue_for_processing method is throwing an exception (expected behavior) and stopping the record from saving.

Am I misunderstanding how after_create works? Or is my understanding correct and something funky happening?

Thanks.

Leonaleonanie answered 3/9, 2012 at 2:9 Comment(0)
C
45

Yes, the callbacks are all wrapped up in a transaction.

Basically, the following will cause a rollback:

  • return false from before_save or similar callbacks
  • exception in before_save or similar callbacks
  • exception in after_save or similar callbacks (after_create)

The following do NOT cause a rollback:

  • return false from after_save or similar callbacks
  • exception in after_commit

If you don't want an exception to cause a rollback, use after_commit

Cerebrum answered 3/9, 2012 at 2:13 Comment(4)
Awesome, thanks for the swift response. This was also helpful: rails-bestpractices.com/posts/695-use-after_commitLeonaleonanie
Also, thanks for introducing me to after_commit. I see that it was introduced in Rails3, but I must have missed the memo. I like learning new things :-)Leonaleonanie
Great explanation! +1 for conciseness.Timofei
For anyone using Rails 4, seems to still hold true :) guides.rubyonrails.org/…Bittner

© 2022 - 2024 — McMap. All rights reserved.