为什么不推荐使用 Rails before_update 回调?还有什么选择?

Why is Rails before_update callback deprecated? What's the alternative?

我查看了 https://apidock.com/rails/ActiveRecord/Callbacks/before_update,它说 before_update 已被弃用。有人知道为什么会这样吗?

我有一些代码逻辑需要 运行 特别是在更新现有记录时。 Before_save 在创建和更新时都会被调用,所以我不能使用它。

编辑:我想我可以做到 before_save :do_stuff,如果:!self.new_record?但我觉得这仍然很奇怪..

编辑 2:!self.new_record?在 if: 块内不起作用。我需要把 !self.new_record?实际方法中的逻辑。

我不认为 before_update 在 Rails 中被弃用 6. 我建议使用 api.rubyonrails.org(in this case) as the preferred reference as it more closely follows the API. You can also have a look at the source directly and see that it's still there. Lastly, the latest version of the Rails Guides suggests it is still an available callback。尝试使用 before_update在你的 Rails 6 应用程序中,看看它是否按预期工作。