diff --git a/lib/ancestry/materialized_path.rb b/lib/ancestry/materialized_path.rb index ad28fd4d..41eb84d3 100644 --- a/lib/ancestry/materialized_path.rb +++ b/lib/ancestry/materialized_path.rb @@ -94,8 +94,8 @@ def ancestry_root def child_ancestry_sql %{ - CASE WHEN #{table_name}.#{ancestry_column} IS NULL THEN CAST(#{table_name}.#{primary_key} AS CHAR) - ELSE #{concat("#{table_name}.#{ancestry_column}", "'#{ancestry_delimiter}'", "CAST(#{table_name}.#{primary_key} AS CHAR)")} + CASE WHEN #{table_name}.#{ancestry_column} IS NULL THEN #{concat("#{table_name}.#{primary_key}")} + ELSE #{concat("#{table_name}.#{ancestry_column}", "'#{ancestry_delimiter}'", "#{table_name}.#{primary_key}")} END } end diff --git a/lib/ancestry/materialized_path2.rb b/lib/ancestry/materialized_path2.rb index 5b950a27..47d520f8 100644 --- a/lib/ancestry/materialized_path2.rb +++ b/lib/ancestry/materialized_path2.rb @@ -29,7 +29,7 @@ def ancestry_root end def child_ancestry_sql - concat("#{table_name}.#{ancestry_column}", "CAST(#{table_name}.#{primary_key} AS CHAR)", "'#{ancestry_delimiter}'") + concat("#{table_name}.#{ancestry_column}", "#{table_name}.#{primary_key}", "'#{ancestry_delimiter}'") end def ancestry_depth_sql diff --git a/test/concerns/counter_cache_test.rb b/test/concerns/counter_cache_test.rb index 011ce909..2093332c 100644 --- a/test/concerns/counter_cache_test.rb +++ b/test/concerns/counter_cache_test.rb @@ -88,16 +88,34 @@ def test_counter_cache_when_updating_record end def test_setting_counter_cache - AncestryTestDatabase.with_model :depth => 2, :width => 2, :counter_cache => true do |model, roots| + AncestryTestDatabase.with_model :depth => 3, :width => 2, :counter_cache => true do |model, roots| + # ensure they are successfully built + roots.each do |lvl0_node, lvl0_children| + assert_equal 2, lvl0_node.reload.children_count + lvl0_children.each do |lvl1_node, lvl1_children| + assert_equal 2, lvl1_node.reload.children_count + lvl1_children.each do |lvl2_node, _lvl2_children| + assert_equal 0, lvl2_node.reload.children_count + end + end + end + model.update_all(model.counter_cache_column => 0) # ensure they are successfully broken roots.each do |lvl0_node, _lvl0_children| assert_equal 0, lvl0_node.reload.children_count end model.rebuild_counter_cache! + # ensure they are successfully built - roots.each do |lvl0_node, _lvl0_children| + roots.each do |lvl0_node, lvl0_children| assert_equal 2, lvl0_node.reload.children_count + lvl0_children.each do |lvl1_node, lvl1_children| + assert_equal 2, lvl1_node.reload.children_count + lvl1_children.each do |lvl2_node, _lvl2_children| + assert_equal 0, lvl2_node.reload.children_count + end + end end end end