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?