[英]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以使其正常工作,但是预期的行为应该是:
quote_file
is created, a quote_file_date
timestamp is created. 当quote_file
被创建,一个quote_file_date
创建时间戳。 quote_file
value changes, the quote_file_date
timestamp is updated. 当quote_file
值更改时, quote_file_date
时间戳会更新。 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.