Rails - Get old value in before_save Rails - Get old value in before_save ruby-on-rails ruby-on-rails

Rails - Get old value in before_save


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.


Instead of before_save use before_update. It should work now.


So, the answer above might work but what if I wanted to get the previous value for some reason and use it to perform some task then you would need to get the previous value. In my case I used this

after_update do  if self.quantity_changed?    sku.decrement(:remaining, (self.quantity_was - self.quantity) * sku.quantity)  endend

The _was and _changed? added to any of the columns would do the job to get the job done.