我正在尝试获得一个before_update
模型回调工作,其中quote_file_date
自动根据是否创建,更新或删除quote_file
自动时间戳。目的是为了使我可以在创建和更新文件时跟踪。
我不确定如何实现ActiveModel :: Dirty无法正常工作,但是预期的行为应该是:
- 创建
quote_file
时,创建了quote_file_date
时间戳。 - 当
quote_file
值更改时,quote_file_date
时间戳将更新。 - 如果删除了
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? }