Is there any difference between:

after_create :after_create and after_commit :after_commit_on_create, :on => :create

Can these be used interchangeably?

推荐答案

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 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).

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.

Ruby-on-rails相关问答推荐

HTTP:MimeNegotiation::InvalidType(html不是有效的MIME类型):""

方法和括号之间没有空格时出错

使用ImportMaps将HighLightJS添加到rails 7.1

Rails ActiveRecord::LogSubscriber 不输出详细查询日志(log)

为什么 2 个关键字参数被解释为 1?

删除 aws s3 (rails7) 上的日志(log)文件

线程如何在 Web 应用程序中工作?

Rspec期望()与期望{}

别名可能与不同模型的相同别名有许多关联?

Rails 和 jsonb 类型jsonb不存在

Heroku 应用程序上的远程 mysql 数据库

ruby on rails 和 javascript 之间的时间转换反之亦然?

如何将实例变量传递给 RSpec 共享示例

Rails 模型方法 self.与普通

如何避免 has_many :through 关系中的重复?

在 Rails 中将表格行变成链接

未选中时,如何使 check_box_tag 发布false或0参数?

在 Ruby on Rails 中循环对象属性

在 Devise on Rails beta 3 中创建管理员用户

在控制台之外运行 Rails 命令