Rails - get old value in before_save

I am trying to get the old value in before_save by adding "_was" to my value, but it does not 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" received a new title that was saved.

Is it possible to get the old value inside before_save ?

+6
source share
3 answers

Use before_update . Now it should work.

+5
source

The reason that you get the same value is most likely because you check the output when creating the record. The before_save is called for both create() and update() , but with create() both title and title_was are assigned the same initial values. Therefore, the answer is β€œyes, you can get the old value inside before_save ”, but you must remember that it will differ from the current value only if the record was actually changed. This means that the results you get are correct because the question change does not occur when the record is created.

+2
source

So, the answer above might work, but what if I wanted to get the previous value for some reason and use it to accomplish 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) end end 

_was and _changed? added to any of the columns will complete the task to complete the task.

0
source

Source: https://habr.com/ru/post/984724/


All Articles