I have two models: Category and Ad. Category has_many :ads + I added counter cache :ads_count. I use gem awesome_nested_set to make nested categories, so Category1 can be parent/child of Category2 which can be parent of Category3 etc. What I need for my categories#index is to calculate total sum of ads which belong to certain category or child category(or "grandchild" etc). My solution for now is: some_nested_categories.sum(:ads_count). But let's say if I have many many categories in my index page, it makes many queries to retrieve all that data and it takes too long. How can I make this more efficiently? Thanks for help!
Sum of counts for nested models
462 Views Asked by AudioBubble At
1
There are 1 best solutions below
Related Questions in RUBY-ON-RAILS
- How to display legend box in tooltip text for amCharts 5 in Rails application?
- how to integrate cashfree payment gateway in ruby on rails project
- RSpec Capybara throwing Selenium error when trying to click a button with browser confirm
- rails minitest not picking up fixture properly, instance variable not percolating
- Duplicate GET requests - Rails & Heroku
- How to stub out current_user in JWT model for Rspec?
- NameError in Home#index
- Verifying Google Identity OAuth2 token with Ruby
- Error WebMock::NetConnectNotAllowedError in testing with stub using minitest in rails (using Faraday)
- why is mission_control-jobs erroring with load path error?
- Rescuing validation errors from a polymorphic association
- New error on random number assigned to local variable , Rails
- How to fix error in model with gem lockbox
- Images uploaded via Active Storage not displaying in Active Admin or on certain devices
- controller test_methods generating two errors intermittently
Related Questions in NESTED
- Python, Exchange specific values in a nested list
- IF AND OR Nested ArrayFormula not working - What am I missing?
- Subset a nested list by a nested list of indices
- How can I easily assign a value (short notatio) to a property of a nested class in php 8+?
- return all paths in a nested dictionary that also contains a list in python
- Absolute path of a child element within nested structure
- How to sum non-empty successive rows in deeply nested tibbles in R?
- Can a nested object call a method from its nesting object?
- How to group flexbox items with DIV but without influencing layout, as if DIV was not there?
- Streamlit multiple nested buttons, not working
- batch file - nested for loop with wildcards
- ForEach loop won't dynamically add entries
- printing list and variable names in triple nested for loop in R does not behave as expected
- Python - convert from JSON to CSV
- Pyspark how to avoid explode for groups in the top and nested structure (code optimalisation)
Related Questions in COUNTER-CACHE
- Getting couter_cache error when saving record in rails
- Rails 6.1.4 counter_cache issue
- batch video views to redis instead of directly to the db
- What is the best way to store a multi-dimensional counter_cache?
- Rails Counter Cache with Active Storage
- Rails counter cache with has_many: :through
- Is there a way to decrease in counter_culture gem when using column_names?
- Rails reset_counters in counter_cache with conditions
- How trigger counter cache after destroy_all
- Starting a counter cache from greater than 0
- Cakephp 3: Countercache with conditions on the target model
- reset_counters not works for not association field
- counter_cache increments twice
- Rails counter cache with condition
- Counter cache cross settings in Ruby on Rails
Related Questions in AWESOME-NESTED-SET
- What is the best way to find all the leaves or self if leaf in awesome_nested_set?
- Rails 5.1: eager load child records in polymorphic association
- awesome_nested_set gem lft does't have default
- Sum of counts for nested models
- Awesome nestset set ancestor class method
- Carrierwave Uploads stopped working in model with Awesome Nested Set
- How to configure default table columns in awesone_nested_set
- Using awesome_nested_set, how to define a has_many relation with all the descendants as well?
- Rails: Enumerate data in the view with different context
- Rails 4 after_save previous_changes not working
- How to restrict access to models in Ruby on Rails 4 using Pundit and Rolify
- Conversation view for mailbox using awesome_nested_set
- Complex categories drop down that depends on the leaf nodes present
- How to render a tree from an awesome_nested_set and hit the database only once?
- AwesomeNestedSet + Rails 4.1.4 `nested_set_options` throws exception
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
Popular # Hahtags
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?
You could extend the idea of the
counter_cachemanually for a sort ofsum_cache, lets call itnested_ads_count.Then there would be 4 general cases that need to be handled
An
after_updatecallback that updates the parent'snested_ads_countwhen either the current'snested_ads_countorads_countupdates. solves the first case.awesome_nested_set solves the other 2 cases
using an
after_addandafter_removecallbacks recalculate thenested_ads_count.The method to calculate and cache the
nested_ads_countwould look like thisThis method is optimal when the frequency that the count is used is greater than the frequency that it is updated, as it only does the time expensive queries when the number would be updated, and not when the number needs to be seen.
There is one possible pitfall that can happen and that is if you have a loop in your nesting (a > b > a, or even more insidious a > b > c > ... > a) you can get yourself in an infinite loop. I have not seen anything explicitly stating that awesome_nested_set blocks this case.