Jamie's Blog

Lessons from a life of startups, coding, countryside, and kids

:dependent => :destroy not firing

I had a model which wasn’t cleaning up the dependent models, even though the :dependent => :destroy attribute was set on the association:

class PerformancePlan < ActiveRecord::Base
  hasmany :goals, dependent: :destroy
  validatesassociated :goals
end

class Goal < ActiveRecord::Base belongsto :plan, classname: 'PerformancePlan' end

Luckily, I’d written a spec to test that the goals were being cleaned up correctly:
  it "must destroy the goals when deleted" do
    plan = FactoryGirl.create :performanceplan, :withgoals, goalcount: 3
    Goal.count.should eq(3)
    expect {
      plan.destroy
    }.to change(Goal, :count).by(-3)
  end
The log showed now indication of any errors or even an attempt to destroy the goals. To get this working, I needed to remove the validatesassociated property:
class PerformancePlan < ActiveRecord::Base
  has_many :goals, dependent: :destroy
end

class Goal < ActiveRecord::Base belongsto :plan, classname: 'PerformancePlan' end