当属性更新为新值或为零时,Rails Fire模型回调



我正在尝试获得一个before_update模型回调工作,其中quote_file_date自动根据是否创建,更新或删除quote_file自动时间戳。目的是为了使我可以在创建和更新文件时跟踪。

我不确定如何实现ActiveModel :: Dirty无法正常工作,但是预期的行为应该是:

  1. 创建quote_file时,创建了quote_file_date时间戳。
  2. quote_file值更改时,quote_file_date时间戳将更新。
  3. 如果删除了quote_file,则quote_file_date将其设置回NIL。

目前,我有:

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

和我从中获得的错误是:

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

使用模型中的回调实现此目的的最优雅方法是什么?

答案是将before_update回调更改为:

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

最新更新