ruby on rails - Sum of counts for nested models -
i have 2 models: category , ad. category has_many :ads + added counter cache :ads_count. use gem awesome_nested_set make nested categories, category1 can parent/child of category2 can parent of category3 etc. need categories#index calculate total sum of ads belong category or child category(or "grandchild" etc). solution is: some_nested_categories.sum(:ads_count). let's if have many many categories in index page, makes many queries retrieve data , takes long. how can make more efficiently? help!
you extend idea of counter_cache
manually sort of sum_cache
, lets call nested_ads_count
.
then there 4 general cases need handled
- a category gets new add
- a category "moved/added" new parent category"
- a category gets deleted (or removed parent)"
an after_update
callback updates parent's nested_ads_count
when either current's nested_ads_count
or ads_count
updates. solves first case.
awesome_nested_set solves other 2 cases
using after_add
, after_remove
callbacks recalculate nested_ads_count
.
the method calculate , cache nested_ads_count
this
def reset_nested_ads_count self.nested_ads_count = some_nested_categories.sum(:nested_ads_count) + self.ads_count end
this method optimal when frequency count used greater frequency updated, time expensive queries when number updated, , not when number needs seen.
there 1 possible pitfall can happen , if have loop in nesting (a > b > a, or more insidious > b > c > ... > a) can in infinite loop. have not seen explicitly stating awesome_nested_set blocks case.
Comments
Post a Comment