1

我的项目有很多样板副本。

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

这种行为是预期的吗?它与计数器缓存有关吗?

4

1 回答 1

1

它似乎与以下 Rails 问题有关:

https://github.com/rails/rails/issues/16449

我在那里添加了一条评论来描述我的问题。当有解决方案时,我会更新这个答案。

于 2015-12-14T12:40:58.393 回答