Fix that counter_cache breaks with has_many :dependent => :nullify.

[#1196 state:committed]

Signed-off-by: Jeremy Kemper <jeremy@bitsweat.net>
This commit is contained in:
Gabe da Silveira
2009-08-09 13:16:57 -07:00
committed by Jeremy Kemper
parent 8a49af3158
commit 9bc80f4dd1
4 changed files with 32 additions and 3 deletions

View File

@@ -74,6 +74,7 @@ module ActiveRecord
"#{@reflection.primary_key_name} = NULL",
"#{@reflection.primary_key_name} = #{owner_quoted_id} AND #{@reflection.klass.primary_key} IN (#{ids})"
)
@owner.class.update_counters(@owner.id, cached_counter_attribute_name => -records.size) if has_cached_counter?
end
end

View File

@@ -508,6 +508,23 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal 0, new_firm.clients_of_firm.size
end
def test_deleting_updates_counter_cache
topic = Topic.first
assert_equal topic.replies.to_a.size, topic.replies_count
topic.replies.delete(topic.replies.first)
topic.reload
assert_equal topic.replies.to_a.size, topic.replies_count
end
def test_deleting_updates_counter_cache_without_dependent_destroy
post = posts(:welcome)
assert_difference "post.reload.taggings_count", -1 do
post.taggings.delete(post.taggings.first)
end
end
def test_deleting_a_collection
force_signal37_to_load_all_clients_of_firm
companies(:first_firm).clients_of_firm.create("name" => "Another Client")
@@ -553,6 +570,14 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
end
def test_clearing_updates_counter_cache
topic = Topic.first
topic.replies.clear
topic.reload
assert_equal 0, topic.replies_count
end
def test_clearing_a_dependent_association_collection
firm = companies(:first_firm)
client_id = firm.dependent_clients_of_firm.first.id

View File

@@ -317,11 +317,11 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_belongs_to_polymorphic_with_counter_cache
assert_equal 0, posts(:welcome)[:taggings_count]
assert_equal 1, posts(:welcome)[:taggings_count]
tagging = posts(:welcome).taggings.create(:tag => tags(:general))
assert_equal 1, posts(:welcome, :reload)[:taggings_count]
assert_equal 2, posts(:welcome, :reload)[:taggings_count]
tagging.destroy
assert posts(:welcome, :reload)[:taggings_count].zero?
assert_equal 1, posts(:welcome, :reload)[:taggings_count]
end
def test_unavailable_through_reflection

View File

@@ -4,6 +4,7 @@ welcome:
title: Welcome to the weblog
body: Such a lovely day
comments_count: 2
taggings_count: 1
type: Post
thinking:
@@ -11,6 +12,8 @@ thinking:
author_id: 1
title: So I was thinking
body: Like I hopefully always am
comments_count: 1
taggings_count: 1
type: SpecialPost
authorless: