简体   繁体   English

属性更新为新值或为nil时,Rails触发模型回调

[英]Rails fire model callback when attribute updates to a new value or is nil

I'm trying to get a before_update model callback working where quote_file_date is automatically timestamped based off whether quote_file is created, updated or removed. 我试图让一个before_update模型回调的工作,其中quote_file_date自动时间戳的基于断是否quote_file被创建,更新或删除。 The purpose of this is so that I can track when the file is created and updated. 这样做的目的是使我可以跟踪文件的创建和更新时间。

I'm unsure how to implement ActiveModel::Dirty to get this working properly, but the expected behaviour should be: 我不确定如何实现ActiveModel :: Dirty以使其正常工作,但是预期的行为应该是:

  1. When quote_file is created, a quote_file_date timestamp is created. quote_file被创建,一个quote_file_date创建时间戳。
  2. When quote_file value changes, the quote_file_date timestamp is updated. quote_file值更改时, quote_file_date时间戳会更新。
  3. If quote_file is removed, the quote_file_date is set back to nil. 如果quote_file被删除,则quote_file_date设置回nil。

Currently, I have: 目前,我有:

class Job < ActiveRecord::Base

  before_update :quote_file_updated?, on: [:create, :update], if: quote_file.identifier.changed?

  private

  def quote_file_updated?
    self.quote_file_date = Time.now
  end

end

And the error I get back from this is: 我从中得到的错误是:

undefined method `quote_file' for #<Class:0x007fa3bbedfec0>

What is the most elegant way to achieve this using callbacks in the model? 在模型中使用回调实现此目的的最优雅的方法是什么?

答案是将before_update回调更改为:

before_update :quote_file_updated?, on: [:create, :update], if: ->(r) { r.quote_file_changed? }

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

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