简体   繁体   English

Rails - 在 before_save 中获取旧值

[英]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.我试图通过在我的值中添加“_was”来获取before_save中的旧值,但它似乎不起作用。

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. “title_was”和“title”都获得了刚刚保存的新标题。

Is it possible to get the old value inside before_save ?是否可以在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.create()update()上都调用了before_save回调,但在create()上, titletitle_was都被分配了相同的初始值。 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.所以答案是“是的,您可以在before_save中获取旧值”,但您必须记住,只有当记录实际更改时,它才会与当前值不同。 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 .而不是before_save使用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)
  end
end

The _was and _changed? _was 和 _changed? added to any of the columns would do the job to get the job done.添加到任何列都可以完成工作。

In rails 5.1.1 ActiveRecord::AttributeMethods::Dirty provides在 rails 5.1.1 ActiveRecord::AttributeMethods::Dirty 提供

saved_changes()

Link for saved_changes() which returns a hash containing all the changes that were just saved. saved_changes() 的链接,它返回一个包含刚刚保存的所有更改的哈希。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM