mirror of
https://github.com/github/rails.git
synced 2026-04-26 03:00:59 -04:00
Fix: counter_cache should decrement on deleting associated records.
[#1195 state:committed] Signed-off-by: Jeremy Kemper <jeremy@bitsweat.net>
This commit is contained in:
committed by
Jeremy Kemper
parent
355f41d8aa
commit
05f2183747
@@ -202,6 +202,9 @@ module ActiveRecord
|
||||
|
||||
records.each do |record|
|
||||
@target.delete(record)
|
||||
if respond_to?(:cached_counter_attribute_name) && @owner[cached_counter_attribute_name]
|
||||
@owner.class.decrement_counter(cached_counter_attribute_name, @owner.send(@owner.class.primary_key))
|
||||
end
|
||||
callback(:after_remove, record)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -552,6 +552,18 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
|
||||
assert_equal 0, companies(:first_firm).clients_of_firm(true).size
|
||||
end
|
||||
|
||||
def test_deleting_updates_counter_cache
|
||||
post = Post.first
|
||||
|
||||
post.comments.delete(post.comments.first)
|
||||
post.reload
|
||||
assert_equal post.comments(true).size, post.comments_count
|
||||
|
||||
post.comments.delete(post.comments.first)
|
||||
post.reload
|
||||
assert_equal 0, post.comments_count
|
||||
end
|
||||
|
||||
def test_deleting_before_save
|
||||
new_firm = Firm.new("name" => "A New Firm, Inc.")
|
||||
new_client = new_firm.clients_of_firm.build("name" => "Another Client")
|
||||
@@ -605,6 +617,14 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
|
||||
end
|
||||
end
|
||||
|
||||
def test_clearing_updates_counter_cache
|
||||
post = Post.first
|
||||
|
||||
post.comments.clear
|
||||
post.reload
|
||||
assert_equal 0, post.comments_count
|
||||
end
|
||||
|
||||
def test_clearing_a_dependent_association_collection
|
||||
firm = companies(:first_firm)
|
||||
client_id = firm.dependent_clients_of_firm.first.id
|
||||
|
||||
@@ -3,6 +3,9 @@ require 'models/post'
|
||||
require 'models/person'
|
||||
require 'models/reader'
|
||||
require 'models/comment'
|
||||
require 'models/tag'
|
||||
require 'models/tagging'
|
||||
require 'models/author'
|
||||
|
||||
class HasManyThroughAssociationsTest < ActiveRecord::TestCase
|
||||
fixtures :posts, :readers, :people, :comments, :authors
|
||||
@@ -84,6 +87,17 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
|
||||
assert posts(:welcome).reload.people(true).empty?
|
||||
end
|
||||
|
||||
def test_deleting_updates_counter_cache
|
||||
taggable = Tagging.first.taggable
|
||||
taggable.taggings.push(Tagging.new)
|
||||
taggable.reload
|
||||
assert_equal 1, taggable.taggings_count
|
||||
|
||||
taggable.taggings.delete(taggable.taggings.first)
|
||||
taggable.reload
|
||||
assert_equal 0, taggable.taggings_count
|
||||
end
|
||||
|
||||
def test_replace_association
|
||||
assert_queries(4){posts(:welcome);people(:david);people(:michael); posts(:welcome).people(true)}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user