Permalink
Browse files

Records with counter_cache needs to update their parents counter cach…

…e column if they are moved to another node
  • Loading branch information...
1 parent 60349eb commit bac17626d00d68970c06e1338d1bac7336bcf7aa joeljunstrom committed with Mar 3, 2010
Showing with 44 additions and 1 deletion.
  1. +12 −1 lib/active_record/acts/tree.rb
  2. +32 −0 test/acts_as_tree_test.rb
@@ -51,7 +51,9 @@ def acts_as_tree(options = {})
include ActiveRecord::Acts::Tree::InstanceMethods
named_scope :roots, :conditions => "#{configuration[:foreign_key]} IS NULL", :order => #{configuration[:order].nil? ? "nil" : %Q{"#{configuration[:order]}"}}
-
+
+ after_update :update_parents_counter_cache
+
def self.root
roots.first
end
@@ -125,6 +127,15 @@ def descendants(node=self)
def childless
self.descendants.collect{|d| d.children.empty? ? d : nil}.compact
end
+
+ private
+
+ def update_parents_counter_cache
+ if self.respond_to?(:children_count) && parent_id_changed?
+ self.class.decrement_counter(:children_count, parent_id_was)
+ self.class.increment_counter(:children_count, parent_id)
+ end
+ end
end
end
end
View
@@ -48,6 +48,10 @@ class TreeMixin < Mixin
acts_as_tree :foreign_key => "parent_id", :order => "id"
end
+class TreeMixinWithCounterCache < Mixin
+ acts_as_tree :foreign_key => "parent_id", :order => "id", :counter_cache => :children_count
+end
+
class TreeMixinWithoutOrder < Mixin
acts_as_tree :foreign_key => "parent_id"
end
@@ -165,6 +169,34 @@ def test_self_and_siblings
end
+class TreeTestWithCounterCache < Test::Unit::TestCase
+ def setup
+ teardown_db
+ setup_db
+ @root = TreeMixinWithCounterCache.create!
+ @child1 = TreeMixinWithCounterCache.create! :parent_id => @root.id
+ @child1_child1 = TreeMixinWithCounterCache.create! :parent_id => @child1.id
+ @child2 = TreeMixinWithCounterCache.create! :parent_id => @root.id
+ end
+
+ def teardown
+ teardown_db
+ end
+
+ def test_counter_cache
+ assert_equal 2, @root.reload.children_count
+ assert_equal 1, @child1.reload.children_count
+ end
+
+ def test_update_parents_counter_cache
+ @child1_child1.update_attributes(:parent_id => @root.id)
+ assert_equal 3, @root.reload.children_count
+ assert_equal 0, @child1.reload.children_count
+ end
+
+end
+
+
class TreeTestWithEagerLoading < Test::Unit::TestCase
def setup

0 comments on commit bac1762

Please sign in to comment.