Skip to content
Browse files

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

[#1196 state:committed]

Signed-off-by: Jeremy Kemper <jeremy@bitsweat.net>
  • Loading branch information...
1 parent 8a49af3 commit 9bc80f4dd149ee70aa05c352bdd3fec46d22871a @gtd gtd committed with jeremy Aug 9, 2009
View
1 activerecord/lib/active_record/associations/has_many_association.rb
@@ -74,6 +74,7 @@ def delete_records(records)
"#{@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
25 activerecord/test/cases/associations/has_many_associations_test.rb
@@ -508,6 +508,23 @@ def test_deleting_before_save
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 @@ def test_clearing_an_association_collection
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
6 activerecord/test/cases/associations/join_model_test.rb
@@ -317,11 +317,11 @@ def test_both_scoped_and_explicit_joins_should_be_respected
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
3 activerecord/test/fixtures/posts.yml
@@ -4,13 +4,16 @@ welcome:
title: Welcome to the weblog
body: Such a lovely day
comments_count: 2
+ taggings_count: 1
type: Post
thinking:
id: 2
author_id: 1
title: So I was thinking
body: Like I hopefully always am
+ comments_count: 1
+ taggings_count: 1
type: SpecialPost
authorless:

0 comments on commit 9bc80f4

Please sign in to comment.
Something went wrong with that request. Please try again.