Skip to content

Commit

Permalink
Added a before_save callback for cache_depth as well as the existing …
Browse files Browse the repository at this point in the history
…before_validation callback. This ensures that all descendants in a subtree have their depth cache updated when the subtree is moved.
  • Loading branch information
scottatron committed Sep 13, 2011
1 parent 770f2e3 commit 47c331e
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/ancestry/has_ancestry.rb
Expand Up @@ -68,6 +68,7 @@ def has_ancestry options = {}

# Cache depth in depth cache column before save
before_validation :cache_depth
before_save :cache_depth

# Validate depth column
validates_numericality_of depth_cache_column, :greater_than_or_equal_to => 0, :only_integer => true, :allow_nil => false
Expand Down
11 changes: 11 additions & 0 deletions test/has_ancestry_test.rb
Expand Up @@ -472,6 +472,17 @@ def test_depth_caching
end
end

def test_depth_caching_after_subtree_movement
AncestryTestDatabase.with_model :depth => 6, :width => 1, :cache_depth => true, :depth_cache_column => :depth_cache do |model, roots|
node = model.at_depth(3).first
node.update_attributes(:parent => model.roots.first)
assert_equal(1, node.depth_cache)
node.descendants.each do |descendant|
assert_equal(descendant.depth, descendant.depth_cache)
end
end
end

def test_depth_scopes
AncestryTestDatabase.with_model :depth => 4, :width => 2, :cache_depth => true do |model, roots|
model.before_depth(2).all? { |node| assert node.depth < 2 }
Expand Down

0 comments on commit 47c331e

Please sign in to comment.