为什么 after_create_commit 的存在使我的 after_update_commit 永远不会触发?
我看到这样的场景:
class User
def thing; puts "hello"; end
after_update_commit :thing
after_create_commit :thing
end
在执行 user.update first_name: rand
时,after_update_commit
永远不会触发 但如果我注释掉 after_create_commit
,它确实有效。
- 最后宣布的一方获胜。
- 似乎仅适用于 _commit 回调,
- 仅发生在同一方法的多个回调中
这是 Rails 错误还是有原因?
导轨 6.1.4.6
I'm seeing a scenario where i have something like this:
class User
def thing; puts "hello"; end
after_update_commit :thing
after_create_commit :thing
end
the after_update_commit
never fires when doing user.update first_name: rand
but if i comment out after_create_commit
, it does work.
- Whichever one is declared last is the one that wins.
- seems to only be for _commit callbacks
- only happens with multiple callbacks for same method
Is this a Rails bug or is there a reason for this?
rails 6.1.4.6
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
https://guides.rubyonrails.org/active_record_callbacks.html#transaction-callbacks
如果没有条件,则解决方案:
如果有条件,则解决方案(在本例中,更新时为
is_active?
)https://guides.rubyonrails.org/active_record_callbacks.html#transaction-callbacks
solution if don't have conditions:
solution if do have condition (in this case,
is_active?
on update)正如 John Bachir 回答中所说,您可能对创建和更新操作有不同的条件(这些条件可能很复杂)。我最终得到的结论是:
在我看来,它更具可读性(并且不会影响方法本身)。
As it was said in John Bachir answer you may have different conditions for
create
and forupdate
actions (and these conditions may be complicated). I ended up with:It is a little bit more readable (and does not affect the method itself) IMO.