[英]Rails — How do I see old and new model values from an after_save callback?
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
. 创建一个V vpscore
增加1。 现在在我的after_save_v
,我想跟踪p.score
的旧值。 How can I do this? 我怎样才能做到这一点?
Using a p.score_was does not work. 使用p.score_was不起作用。
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? 还是在after_save回调中这是不可能的?
In after_save
, if you use the changes
method, it returns the hash of all the changes on your object. 在after_save
,如果使用changes
方法,它将返回对象上所有更改的哈希值。 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"]
. 在您的示例中,它可以是self.p.changes["score"]
。 This returns an array [0, 1]
, where 0
is the old value, and 1
is the new value 这将返回一个数组[0, 1]
,其中0
是旧值,而1
是新值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.