Jamie's Weblog

Procrastination and utter drivel since 2001!
  • Email
  • Github
  • Linkedin
  • Twitter
  • Rss
  • Home
  • About
  • Archives
  • Publications
Home» Ruby on Rails » :dependent => :destroy not firing

:dependent => :destroy not firing

Posted on August 25, 2012 by Jamie Lawrence in Ruby on Rails, Tips & Tricks

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
  has_many :goals, dependent: :destroy
  validates_associated :goals
end

class Goal < ActiveRecord::Base
  belongs_to :plan, class_name: '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 :performance_plan, :with_goals, goal_count: 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 validates_associated property:

class PerformancePlan < ActiveRecord::Base
  has_many :goals, dependent: :destroy
end

class Goal < ActiveRecord::Base
  belongs_to :plan, class_name: 'PerformancePlan'
end
activerecord, models, rails No Comments

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Contact Me

  • jamie@ideasasylum.com
  • ideasasylum
    • Twitter

Categories

  • BalanceTrackr (2)
  • C# (1)
  • dualpricing.ie (2)
  • hack (1)
  • Java (4)
  • Linux (3)
  • Measure it to change it (2)
  • Parenting (2)
  • Personal (36)
  • Photography (13)
  • Projects (7)
  • Python (3)
  • rant (20)
  • Reviews (20)
  • Ruby on Rails (18)
  • Taskmonifier (1)
  • Tech (1)
  • Tips & Tricks (7)
  • tuesdaypush (1)
  • Uncategorized (877)
  • Useful (3)
  • Weekly Picks (5)
  • Work (2)

Tags

accident backups barcampcork batteries bizcamp business car copyright depression dual pricing eneloop fowadublin fun gallstones git svn health ipad iphone lens life motivation nginx Personal phd photographers photography photos pinterest podcasts prism quote rails rant renault scenic review rspec ruby sew shutterscouts ssl startups swimming vagrant windows wrap

Meta

  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org

(c) 2012 Jamie's Weblog