Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Counter cache column #619

Merged
merged 1 commit into from
Mar 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 1 addition & 6 deletions lib/ancestry/has_ancestry.rb
Original file line number Diff line number Diff line change
Expand Up @@ -87,12 +87,7 @@ def has_ancestry options = {}
# Create counter cache column accessor and set to option or default
if options[:counter_cache]
cattr_accessor :counter_cache_column

if options[:counter_cache] == true
self.counter_cache_column = :children_count
else
self.counter_cache_column = options[:counter_cache]
end
self.counter_cache_column = options[:counter_cache] == true ? 'children_count' : options[:counter_cache].to_s

after_create :increase_parent_counter_cache, if: :has_parent?
after_destroy :decrease_parent_counter_cache, if: :has_parent?
Expand Down
12 changes: 4 additions & 8 deletions lib/ancestry/instance_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def touch_ancestors_callback

# Counter Cache
def increase_parent_counter_cache
self.ancestry_base_class.increment_counter _counter_cache_column, parent_id
self.ancestry_base_class.increment_counter counter_cache_column, parent_id
end

def decrease_parent_counter_cache
Expand All @@ -86,7 +86,7 @@ def decrease_parent_counter_cache
return if defined?(@_trigger_destroy_callback) && !@_trigger_destroy_callback
return if ancestry_callbacks_disabled?

self.ancestry_base_class.decrement_counter _counter_cache_column, parent_id
self.ancestry_base_class.decrement_counter counter_cache_column, parent_id
end

def update_parent_counter_cache
Expand All @@ -95,14 +95,10 @@ def update_parent_counter_cache
return unless changed

if parent_id_was = parent_id_before_last_save
self.ancestry_base_class.decrement_counter _counter_cache_column, parent_id_was
self.ancestry_base_class.decrement_counter counter_cache_column, parent_id_was
end

parent_id && self.ancestry_base_class.increment_counter(_counter_cache_column, parent_id)
end

def _counter_cache_column
self.ancestry_base_class.counter_cache_column.to_s
parent_id && increase_parent_counter_cache
end

# Ancestors
Expand Down