使用ActiveRecord,有一种方法可以在after_update期间获取记录的旧值 [英] Using ActiveRecord, is there a way to get the old values of a record during after_update
问题描述
使用简单示例进行设置:我有一个表( Totals
),其中包含 (
列。 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
.
现在我在期间减去
并在 self.amount
before_update 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.
这说...
ActiveRecord从Rails 2.1开始跟踪对象的属性值。因此,如果你有一个属性 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 any more.
更新:这是 ActiveRecord :: Dirty 。
这篇关于使用ActiveRecord,有一种方法可以在after_update期间获取记录的旧值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!