Permalink
Browse files

Ensure HasManyThroughAssociation#destroy delete orphan records [#2251

…state:resolved]

Signed-off-by: Pratik Naik <pratiknaik@gmail.com>
  • Loading branch information...
1 parent 97b75c9 commit 7a85927da21859a6868c3e0ec92267706b0a14bf Luca Guidi committed with lifo Mar 16, 2009
@@ -22,6 +22,13 @@ def create(attrs = nil)
end
end
+ def destroy(*records)
+ transaction do
+ delete_records(flatten_deeper(records))
+ super
+ end
+ 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.
@@ -93,7 +93,7 @@ def test_delete_association
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 @@ def test_destroy_association
end
def test_destroy_all
- assert_difference "Person.count", -1 do
+ 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 comment on commit 7a85927

lylo commented on 7a85927 May 19, 2009

Since this commit I'm seeing issues calling 'destroy_all' on a has_many :through association.

Given:

has_many :projects, :thought => contacts

Previously, a call to "projects.destroy_all" was fine, but since this commit I get the following error:

ActiveRecord::HasManyThroughCantAssociateThroughHasManyReflection: Cannot modify association 'MyClass#projects' because the source reflection class 'Project' is associated to 'Contact' via :has_many

Is this expected behaviour?

Please sign in to comment.