Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Get old value in before_save

I'm trying to get the old value in the before_save by adding "_was" to my value but it doesn't seem to work.

Here is my code:

before_save :get_old_title

def get_old_title
    puts "old value #{self.title_was} =>  #{self.title}"
  end

Both "title_was" and "title" got the new title just been saved.

Is it possible to get the old value inside before_save ?

like image 854
user2037696 Avatar asked Apr 06 '15 04:04

user2037696


1 Answers

The reason for you getting the same value is most probably because you check the output when creating the record. The callback before_save is called on both create() and update() but on create() both title and title_was are assigned the same, initial value. So the answer is "yes, you can get the old value inside before_save" but you have to remember that it will be different than the current value only if the record was actually changed. This means that the results you are getting are correct, because the change in question doesn't happen when the record is created.

like image 165
silverdr Avatar answered Oct 23 '22 06:10

silverdr