user645579
user645579

Reputation:

Keeping the previous value of an attribute

I have the following situation: If the name attribute of my student object changes, I want to keep the old value and save it to another table.

So, If I have a student object with the name attribute 'John 1', after a student.update_attributes(:name => 'John 2') I want to be able to capture the old name value 'John 1' in a before_update callback hook, for instance. What's the best way to do that ? Thanks in advance.

Upvotes: 0

Views: 1238

Answers (1)

Dylan Markow
Dylan Markow

Reputation: 124479

In the before_update hook, you can access special _was methods to get the previous value of each field

before_update do
  new_name = self.name     # 'John 2'
  old_name = self.name_was # 'John 1'
end

Upvotes: 3

Related Questions