小编slu*_*hie的帖子

Rails、ActiveRecord:#reload 期间运行回调

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

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
Run Code Online (Sandbox Code Playgroud)

我的问题是 Result 对象有时必须调用 #reload 才能从数据库获取新值。是否有一个回调我可以挂钩来清除 的值@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
Run Code Online (Sandbox Code Playgroud)

activerecord ruby-on-rails

3
推荐指数
1
解决办法
2505
查看次数

标签 统计

activerecord ×1

ruby-on-rails ×1