使用ActiveRecord的,有没有办法让在after_update记录的旧值 [英] Using ActiveRecord, is there a way to get the old values of a record during after_update

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

问题描述

用一个简单的例子设置:我有1台(汇总)持有的总和每条记录的第二个表金额列(事情)。

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 得到更新,我想简单地添加旧值和新值之间的差异总。总之

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.

现在,我减去 self.amount before_update 并添加自我。量 after_update 。这地方太多信赖,在更新成功。

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?

更新:我要与卢克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.

这是说...

ActiveRecord的和Rails 2.1跟踪对象的属性值。所以,如果你有一个属性,你将有一个 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 any more.

更新:这里是的ActiveRecord的文件::脏的要求。

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆