gpt4 book ai didi

ruby-on-rails - rails ,ActiveRecord : Callback run during #reload

转载 作者:行者123 更新时间:2023-12-05 01:47:31 32 4
gpt4 key购买 nike

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

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 才能从数据库中获取新值。有没有我可以 Hook 的回调来清除 @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

最佳答案

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

def reload
super

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

关于ruby-on-rails - rails ,ActiveRecord : Callback run during #reload,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25575283/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com