after_commit和after_destroy回调不会在ActiveRecord::Relation delete



我使用ActiveRecord::Relationdelete_by方法删除记录,但这不会触发after_commitafter_destroy回调。请看下面的例子:

class User < ActiveRecord::Base
after_commit :expire_cache
after_destroy :expire_cache
def expire_cache
puts "expire_cache is called"
end
end
User.delete_by(user_id: 1234) # doesn't trigger expire_cache method

我对回调的期望是正确的吗?我做错了什么?

我对回调的期望是正确的吗?

。您期望用delete_by触发回调是错误的。

我做错了什么?

你的理解与文档不符。

根据Doc,跳过回调delete_all将跳过callbacks

  • delete_all与验证一样,也可以跳过回调。
  • 这些方法应该谨慎使用,但是,因为重要的业务规则和应用程序逻辑可能保留在回调中。在不了解潜在影响的情况下绕过它们可能会导致无效数据。

如果你想让你的回调运行,使用destroy_by代替:

User.destroy_by(id: 1234)

这些方法是在Rails 6中引入的。更多信息在这里:

  • https://blog.saeloun.com/2019/10/15/rails-6-delete-by-destroy-by.html
  • https://github.com/rails/rails/issues/35304

了解deletedestroy之间的差异也有帮助:Destroy和Delete的区别

最新更新