我正在尝试使用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>
使用模型中的回调实现此目的的最优雅方法是什么?
答案 0 :(得分:0)
答案是将before_update
回调更改为:
before_update :quote_file_updated?, on: [:create, :update], if: ->(r) { r.quote_file_changed? }