我的项目有很多样板副本。
class Project < ActiveRecord::Base
has_many :boilerplate_copies, dependent: :destroy
end
class BoilerplateCopy < Boilerplate
belongs_to :project, counter_cache: true
belongs_to :boilerplate_original
end
我有以下规格:
it 'destroys associated boilerplate copies' do
project = Project.create! name: 'my project', customer: 'some customer'
project.boilerplate_copies.create! title: 'my boilerplate'
expect {
project.destroy
}.to change { BoilerplateCopy.count }.by -1
end
它失败:
Failure/Error: project.destroy
ActiveRecord::StaleObjectError:
Attempted to destroy a stale object: Project
我发现创建关联对象时,数据库中的 lock_version 字段已更新,但 ruby 对象无法识别这一点。因此,当添加 时project.reload
,规范通过:
it 'destroys associated boilerplate copies' do
project = Project.create! name: 'my project', customer: 'some customer'
project.boilerplate_copies.create! title: 'my boilerplate'
project.reload
expect {
project.destroy
}.to change { BoilerplateCopy.count }.by -1
end
这种行为是预期的吗?它与计数器缓存有关吗?