Ruby developer. CTO. Swimmer. Always trying to write more
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 endLuckily, I’d written a spec to test that the goals were being cleaned up correctly:class Goal < ActiveRecord::Base belongsto :plan, classname: 'PerformancePlan' end
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) endThe 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 endclass Goal < ActiveRecord::Base belongsto :plan, classname: 'PerformancePlan' end