Rails 当属性更新为新值或为 nil 时触发模型回调
Rails fire model callback when attribute updates to a new value or is nil
我正在尝试让 before_update
模型回调工作,其中 quote_file_date
会根据是否创建、更新或删除 quote_file
自动添加时间戳。这样做的目的是让我可以跟踪文件的创建和更新时间。
我不确定如何实施 ActiveModel::Dirty 才能使其正常工作,但预期的行为应该是:
- 创建
quote_file
时,会创建一个 quote_file_date
时间戳。
- 当
quote_file
值更改时,quote_file_date
时间戳会更新。
- 如果删除
quote_file
,quote_file_date
将设置回零。
目前,我有:
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? }
我正在尝试让 before_update
模型回调工作,其中 quote_file_date
会根据是否创建、更新或删除 quote_file
自动添加时间戳。这样做的目的是让我可以跟踪文件的创建和更新时间。
我不确定如何实施 ActiveModel::Dirty 才能使其正常工作,但预期的行为应该是:
- 创建
quote_file
时,会创建一个quote_file_date
时间戳。 - 当
quote_file
值更改时,quote_file_date
时间戳会更新。 - 如果删除
quote_file
,quote_file_date
将设置回零。
目前,我有:
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? }