From 69c63dd9c09125666aab2e8132ccbe21c143d6f7 Mon Sep 17 00:00:00 2001 From: Luca Guidi Date: Mon, 16 Mar 2009 12:14:13 +0100 Subject: [PATCH] Ensure HasManyThroughAssociation#destroy delete orphan records --- .../associations/has_many_through_association.rb | 5 +++++ .../has_many_through_associations_test.rb | 12 +++++++++--- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/activerecord/lib/active_record/associations/has_many_through_association.rb b/activerecord/lib/active_record/associations/has_many_through_association.rb index 1c091e7..116703b 100644 --- a/activerecord/lib/active_record/associations/has_many_through_association.rb +++ b/activerecord/lib/active_record/associations/has_many_through_association.rb @@ -22,6 +22,11 @@ module ActiveRecord end end + def destroy(*records) + super + delete_records(flatten_deeper(records)) + end + # Returns the size of the collection by executing a SELECT COUNT(*) query if the collection hasn't been loaded and # calling collection.size if it has. If it's more likely than not that the collection does have a size larger than zero, # and you need to fetch that collection afterwards, it'll take one fewer SELECT query if you use #length. diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index 97efca7..f2820e4 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -93,7 +93,7 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase end def test_destroy_association - assert_difference "Person.count", -1 do + assert_difference ["Person.count", "Reader.count"], -1 do posts(:welcome).people.destroy(people(:michael)) end @@ -102,14 +102,20 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase end def test_destroy_all - assert_difference "Person.count", -1 do - posts(:welcome).people.destroy_all + assert_difference ["Person.count", "Reader.count"], -1 do + posts(:welcome).people.destroy_all end assert posts(:welcome).reload.people.empty? assert posts(:welcome).people(true).empty? end + def test_should_raise_exception_for_destroying_mismatching_records + assert_no_difference ["Person.count", "Reader.count"] do + assert_raise(ActiveRecord::AssociationTypeMismatch) { posts(:welcome).people.destroy(posts(:thinking)) } + end + end + def test_replace_association assert_queries(4){posts(:welcome);people(:david);people(:michael); posts(:welcome).people(true)} -- 1.5.4.5