Skip to content

Commit

Permalink
Add support for virtual depth column
Browse files Browse the repository at this point in the history
still need to consider whether to keep depth_cache_column as deprecated
  • Loading branch information
kbrock committed Oct 22, 2024
1 parent 4dda866 commit 9266e89
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
6 changes: 5 additions & 1 deletion lib/ancestry/has_ancestry.rb
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,11 @@ def has_ancestry options = {}
end

# Create ancestry column accessor and set to option or default
if options[:cache_depth]

if options[:cache_depth] == :virtual
# NOTE: not setting self.depth_cache_column so the code does not try to update the column
depth_cache_sql = options[:depth_cache_column]&.to_s || 'ancestry_depth'
elsif options[:cache_depth]
# Create accessor for column name and set to option or default
self.cattr_accessor :depth_cache_column
self.depth_cache_column =
Expand Down
15 changes: 14 additions & 1 deletion test/environment.rb
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,20 @@ def self.with_model options = {}

ActiveRecord::Base.connection.create_table 'test_nodes', **table_options do |table|
table.send(column_type, options[:ancestry_column], **column_options(force_allow_nil: skip_ancestry))
table.integer options[:cache_depth] == true ? :ancestry_depth : options[:cache_depth] if options[:cache_depth]
case options[:cache_depth]
when true
table.integer :ancestry_depth
when :virtual
# sorry, this duplicates has_ancestry a little
path_module = Ancestry::HasAncestry.ancestry_format_module(options[:ancestry_format])
ancestry_depth_sql = path_module.construct_depth_sql("test_nodes", options[:ancestry_column], '/')

table.virtual :ancestry_depth, type: :integer, as: ancestry_depth_sql, stored: true
when nil, false
# no column
else
table.integer options[:cache_depth]
end
if options[:counter_cache]
counter_cache_column = options[:counter_cache] == true ? :children_count : options[:counter_cache]
table.integer counter_cache_column, default: 0, null: false
Expand Down

0 comments on commit 9266e89

Please sign in to comment.