Skip to content

Commit

Permalink
In tests, change child_count cache column to default to 0
Browse files Browse the repository at this point in the history
Before
======

New records had the children counter cache value of nil.

On mysql, update_counter_cache sets nodes with no children to nil.

After
=====

New records have the children counter cache set to 0

On mysql, update_counter_cache now sets to 0 (was nil)
new records set the nodes with no children to have a count of 0.

Docs
====

Looks like there is no documentation for the child counter cache.
Need to add to the README\
  • Loading branch information
kbrock committed Jul 13, 2023
1 parent 0e17fe5 commit 49484a3
Show file tree
Hide file tree
Showing 3 changed files with 4 additions and 4 deletions.
2 changes: 1 addition & 1 deletion lib/ancestry/class_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ def rebuild_counter_cache!
JOIN #{table_name} children ON children.#{ancestry_column} = (#{child_ancestry_sql})
GROUP BY #{table_name}.#{primary_key}
) src USING(#{primary_key})
SET dest.#{counter_cache_column} = src.child_count
SET dest.#{counter_cache_column} = COALESCE(src.child_count, 0)
}
else
update_all %{
Expand Down
4 changes: 2 additions & 2 deletions test/concerns/sti_support_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,10 @@ def test_sti_support_for_counter_cache
node5 = Subclass3.create! :parent => node4

assert_equal 2, node1.reload.children_count
assert_nil node2.reload.children_count
assert_equal 0, node2.reload.children_count
assert_equal 1, node3.reload.children_count
assert_equal 1, node4.reload.children_count
assert_nil node5.reload.children_count
assert_equal 0, node5.reload.children_count

Object.send :remove_const, 'Subclass3'
Object.send :remove_const, 'Subclass4'
Expand Down
2 changes: 1 addition & 1 deletion test/environment.rb
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ def self.with_model options = {}
table.integer options[:cache_depth] == true ? :ancestry_depth : options[:cache_depth] if options[:cache_depth]
if options[:counter_cache]
counter_cache_column = options[:counter_cache] == true ? :children_count : options[:counter_cache]
table.integer counter_cache_column
table.integer counter_cache_column, default: 0, null: false
end

extra_columns.each do |name, type|
Expand Down

0 comments on commit 49484a3

Please sign in to comment.