本文介绍了使用 ActiveRecord,有没有办法在 after_update 期间获取记录的旧值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用简单示例进行设置:我有 1 个表 (Totals),其中包含每条记录的 amount 列的总和在第二个表中 (Things).

Setup using a simple example: I've got 1 table (Totals) that holds the sum of the amount column of each record in a second table (Things).

thing.amount 更新时,我想简单地将旧值和新值之间的差异添加到 total.sum.

When a thing.amount gets updated, I'd like to simply add the difference between the old value and the new value to total.sum.

现在我在 before_update 期间减去 self.amount 并在 after_update 期间添加 self.amount.这让 WAY 过于相信更新成功.

Right now I'm subtracting self.amount during before_update and adding self.amount during after_update. This places WAY too much trust in the update succeeding.

约束:我不想简单地重新计算所有交易的总和.

Constraint: I don't want to simply recalculate the sum of all the transactions.

问题: 很简单,我想在 after_update 回调期间访问原始值.你想出了什么方法来做到这一点?

Question: Quite simply, I'd like to access the original value during an after_update callback. What ways have you come up with do this?

更新:我同意 Luke Francl 的想法.在 after_update 回调期间,您仍然可以访问 self.attr_was 值,这正是我想要的.我还决定采用 after_update 实现,因为我想在模型中保留这种逻辑.这样,无论我将来如何决定更新事务,我都会知道我正在正确更新事务的总和.感谢大家提出实施建议.

Update: I'm going with Luke Francl's idea. During an after_update callback you still have access to the self.attr_was values which is exactly what I wanted. I also decided to go with an after_update implementation because I want to keep this kind of logic in the model. This way, no matter how I decide to update transactions in the future, I'll know that I'm updating the sum of the transactions correctly. Thanks to everyone for your implementation suggestions.

推荐答案

同上每个人对交易的看法.

Ditto what everyone is saying about transactions.

说...

从 Rails 2.1 开始,ActiveRecord 会跟踪对象的属性值.因此,如果您有一个属性 total,您将有一个 total_changed? 方法和一个返回旧值的 total_was 方法.

ActiveRecord as of Rails 2.1 keeps track of the attribute values of an object. So if you have an attribute total, you will have a total_changed? method and a total_was method that returns the old value.

无需再向您的模型添加任何内容来跟踪此情况.

There's no need to add anything to your model to keep track of this anymore.

更新:这里是 ActiveModel::Dirty 的文档 根据要求.

这篇关于使用 ActiveRecord,有没有办法在 after_update 期间获取记录的旧值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 06:42