1

My projects have many boilerplate copies.

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

I have the following spec:

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

It fails:

Failure/Error: project.destroy
ActiveRecord::StaleObjectError:
  Attempted to destroy a stale object: Project

I have found out that the lock_version field is updated in the DB when an associated object is created, but the ruby object doesn't recognise this. So when adding project.reload, the spec passes:

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

Is this behaviour expected? Does it have to do with the counter cache?

Joshua Muheim
  • 12,617
  • 9
  • 76
  • 152

1 Answers1

1

It seems to have to do with the following Rails issue:

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

I have added a comment there describing my issue. When there is a solution, I will updated this answer.

Joshua Muheim
  • 12,617
  • 9
  • 76
  • 152