Let's say I have the following models:
class V < ActiveRecord::Base
belongs_to :p
after_save :after_save_v
...
end
class P < ActiveRecord::Base
has_many :vs
# Has an attribute called "score" (defined in the DB table)
...
end
Creating a V increases vpscore
by 1. Now in my after_save_v
, I would like to track the old value of p.score
. How can I do this?
Using a p.score_was does not work.
class V < ActiveRecord::Base
def after_save_v
puts p.score_was # => 1
puts p.score # => 1
end
end
What am I missing here? Or is this something that is not possible from the after_save callback?
In after_save
, if you use the changes
method, it returns the hash of all the changes on your object. You can specify which attribute's changes you need. This will be an array. [old-value, new-value]
In your Example, it can be self.p.changes["score"]
. This returns an array [0, 1]
, where 0
is the old value, and 1
is the new value
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.