Rails,ActiveRecord:在#reload期间运行回调

时间:2014-08-29 19:51:36

标签: ruby-on-rails activerecord

我有一个模型,其属性是根据持久列值的值生成的。

class Result < ActiveRecord::Base
  belongs_to :job
  belongs_to :customer
  has_many :records, through: :job

  def processed_records
    @processed_records ||=
      begin
        status_flagged + status_invalid +
          status_unknown + status_valid
      end
  end
end

我的问题是Result对象有时必须调用#reload来从DB获取新值。我是否可以使用回调清除@processed_records的值,以便下次调用将重新计算该值?

换句话说,我希望这样做:

RSpec.describe Result, :type => :model do
  subject { create(:result) }

  it 'should update #processed_records on reload' do
    initial_value = subject.processed_records

    other_instance = Result.find(subject.id)
    other_instance.increment(:status_flagged)
    other_instance.save

    subject.reload
    expect(subject.processed_records).to eq(initial_value + 1)
  end
end

1 个答案:

答案 0 :(得分:1)

您可以覆盖模型中的reload方法:

def reload
  super

  # code with whatever you need to clean, for example:
  @processed_records = nil
end