Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 797
Abel Avatar asked Mar 03 '09 16:03

Abel


People also ask

What does Active Record base do?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.

What is Ruby Active Record?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.

What is an Active Record object?

In Active Record, objects carry both persistent data and behavior which operates on that data. Active Record takes the opinion that ensuring data access logic as part of the object will educate users of that object on how to write to and read from the database.


2 Answers

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.

like image 73
Luke Francl Avatar answered Sep 17 '22 13:09

Luke Francl


Appending "_was" to your attribute will give you the previous value before saving the data.

These methods are called dirty methods methods.

Cheers!

like image 35
Manish Shrivastava Avatar answered Sep 19 '22 13:09

Manish Shrivastava