Rails:after_create 中的异常停止保存 [英] Rails: Exception in after_create stopping save
问题描述
简单的问题.我有一个 ActiveRecord 模型,我想在保存记录后对其进行后期处理.所以在模型中,我有一个 queue_for_processing 方法,可以将作业粘贴到我的 Resque 队列中.为了在我的记录成功保存后执行此操作,我在我的模型中编写了以下内容:
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
很简单.我原以为一切都按预期进行,除了昨晚我的 redis 服务器出现故障并且出现问题.我的期望是该记录仍会被保存,并且我可以稍后手动处理该作业.但是 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.
我是否误解了 after_create 的工作原理?或者我的理解是否正确并且发生了一些时髦的事情?
Am I misunderstanding how after_create works? Or is my understanding correct and something funky happening?
谢谢.
推荐答案
是的,回调都包含在一个事务中.
Yes, the callbacks are all wrapped up in a transaction.
基本上,以下会导致回滚:
Basically, the following will cause a rollback:
- 从
before_save
或类似回调返回 false before_save
或类似回调中的异常after_save
或类似回调(after_create)中的异常
- return false from
before_save
or similar callbacks - exception in
before_save
or similar callbacks - exception in
after_save
or similar callbacks (after_create)
以下不会导致回滚:
- 从
after_save
或类似回调返回 false after_commit
中的异常
- return false from
after_save
or similar callbacks - exception in
after_commit
如果您不希望异常导致回滚,请使用 after_commit
If you don't want an exception to cause a rollback, use after_commit
- 参考:http://webonrails.com/2012/08/28/activerecord-after_commit-钩子/
- 附加参考:http://guides.rubyonrails.org/v3.1.3/active_record_validations_callbacks.html#transaction-callbacks
这篇关于Rails:after_create 中的异常停止保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!