Using ActiveRecord, is there a way to get the old values of a record during after_update

Abel picture Abel · Mar 3, 2009 · Viewed 49.2k times · Source

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).

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.

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.

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?

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.

Answer

Luke Francl picture Luke Francl · Mar 3, 2009

Ditto what everyone is saying about transactions.

That said...

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.

Update: Here is the documentation for ActiveModel::Dirty as requested.