From 61377e514ba31c333411e1611aaf1afe9e92f65e Mon Sep 17 00:00:00 2001 From: Filipe Giusti Date: Tue, 17 May 2011 17:43:59 -0300 Subject: [PATCH] counter_cache isn't decremented when a model with a self referential association is destroyed --- .../associations/has_many_associations_test.rb | 13 +++++++++++++ activerecord/test/models/author.rb | 7 ++++--- activerecord/test/schema/schema.rb | 2 ++ 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 522ac56..9cfdee9 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -718,6 +718,19 @@ class HasManyAssociationsTest < ActiveRecord::TestCase end end + def test_deleting_updates_counter_cache_with_dependent_destroy_in_self_referential_association + david = authors(:david) + mary = authors(:mary) + david.author_favorites.create(:favorite_author_id => mary.id) + david.author_fans.create(:author_id => mary.id) + + mary.destroy + + david.reload + assert_equal 0, david.author_fans_count + assert_equal 0, david.author_favorites_count + end + def test_deleting_updates_counter_cache_with_dependent_delete_all post = posts(:welcome) post.update_column(:taggings_with_delete_all_count, post.taggings_count) diff --git a/activerecord/test/models/author.rb b/activerecord/test/models/author.rb index e0cbc44..8e0b147 100644 --- a/activerecord/test/models/author.rb +++ b/activerecord/test/models/author.rb @@ -91,7 +91,8 @@ class Author < ActiveRecord::Base has_many :nothings, :through => :kateggorisatons, :class_name => 'Category' - has_many :author_favorites + has_many :author_favorites, :dependent => :destroy + has_many :author_fans, :dependent => :destroy, :class_name => "AuthorFavorite", :foreign_key => :favorite_author_id has_many :favorite_authors, :through => :author_favorites, :order => 'name' has_many :tagging, :through => :posts @@ -193,6 +194,6 @@ class AuthorAddress < ActiveRecord::Base end class AuthorFavorite < ActiveRecord::Base - belongs_to :author - belongs_to :favorite_author, :class_name => "Author" + belongs_to :author, :counter_cache => "author_favorites_count" + belongs_to :favorite_author, :class_name => "Author", :counter_cache => "author_fans_count" end diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb index 4fe311b..e28bdf2 100644 --- a/activerecord/test/schema/schema.rb +++ b/activerecord/test/schema/schema.rb @@ -55,6 +55,8 @@ ActiveRecord::Schema.define do t.integer :author_address_extra_id t.string :organization_id t.string :owned_essay_id + t.integer :author_favorites_count + t.integer :author_fans_count end create_table :author_addresses, :force => true do |t| -- 1.7.1