当属性更新为新值或为nil时,Rails会触发模型回调

时间:2015-05-05 16:32:03

标签: ruby-on-rails ruby ruby-on-rails-4 model activemodel

我正在尝试使用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。
  4. 目前,我有:

    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>
    

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

1 个答案:

答案 0 :(得分:0)

答案是将before_update回调更改为:

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