after_create :foo vs after_commit :bar, :on =>:创造 [英] after_create :foo vs after_commit :bar, :on => :create

查看:50
本文介绍了after_create :foo vs after_commit :bar, :on =>:创造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么区别:

after_create :after_createafter_commit :after_commit_on_create, :on =>:创建

这些可以互换使用吗?

推荐答案

它们不可互换.主要区别在于回调运行的时间.在after_create 的情况下,这将始终在对save(或create)的调用返回之前.

They are not interchangeable. The key difference is when the callback runs. In the case of after_create, this will always be before the call to save (or create) returns.

Rails 将每个 save 包装在一个事务中,并且在该事务中运行 before/after create 回调(结果是,如果在 after_create 中引发异常,则保存将回滚).使用 after_commit,您的代码直到最外层事务提交后才会运行.这可能是事务轨道创建的或由您创建的(例如,如果您想在单个事务中进行多项更改).

Rails wraps every save inside a transaction and the before/after create callbacks run inside that transaction (a consequence of this is that if an exception is raised in an after_create the save will be rolled back). With after_commit, your code doesn't run until after the outermost transaction was committed. This could be the transaction rails created or one created by you (for example if you wanted to make several changes inside a single transaction).

after_save/create 运行时,您的保存仍然可以回滚,并且(默认情况下)其他数据库连接(例如,sidekiq 等后台任务)将不可见.这两者的某种组合通常是使用 after_commit 的动机.

At the point when after_save/create runs, your save could still be rolled back and (by default) won't be visible to other database connections (e.g. a background task such as sidekiq). Some combination of these 2 is usually the motivation for using after_commit.

这篇关于after_create :foo vs after_commit :bar, :on =>:创造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆