1
我有一个模型,它具有从持久列值的值生成的属性。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
我的问题是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
'高清重装;超; @processed_records = nil;结束? – 2014-08-29 19:53:36
试一试'after_find' – Aguardientico 2014-08-29 19:56:17
@MarianTheisen是的,这将工作......我只是希望有更多的语义相关的东西,沿'after_update'行。 – slushie 2014-08-29 20:01:59