Rails: Exception in after_create stopping save

倖福魔咒の 提交于 2019-12-18 02:01:29

问题


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.


回答1:


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

  • Reference: http://webonrails.com/2012/08/28/activerecord-after_commit-hook/
  • Additional reference: http://guides.rubyonrails.org/v3.1.3/active_record_validations_callbacks.html#transaction-callbacks


来源:https://stackoverflow.com/questions/12241244/rails-exception-in-after-create-stopping-save

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!