diff --git a/app/models/category.rb b/app/models/category.rb index 9a7597fe5..50c7f0f7f 100644 --- a/app/models/category.rb +++ b/app/models/category.rb @@ -44,6 +44,7 @@ class Category < ActiveRecord::Base has_one :category_search_data belongs_to :parent_category, class_name: 'Category' + has_many :subcategories, class_name: 'Category', foreign_key: 'parent_category_id' scope :latest, ->{ order('topic_count desc') } diff --git a/app/serializers/category_detailed_serializer.rb b/app/serializers/category_detailed_serializer.rb index 8551255ea..405c129fe 100644 --- a/app/serializers/category_detailed_serializer.rb +++ b/app/serializers/category_detailed_serializer.rb @@ -17,31 +17,6 @@ class CategoryDetailedSerializer < BasicCategorySerializer has_many :featured_users, serializer: BasicUserSerializer has_many :displayable_topics, serializer: ListableTopicSerializer, embed: :objects, key: :topics - - def topics_week - object.topics_week || 0 - end - - def topics_month - object.topics_month || 0 - end - - def topics_year - object.topics_year || 0 - end - - def posts_week - object.posts_week || 0 - end - - def posts_month - object.posts_month || 0 - end - - def posts_year - object.posts_year || 0 - end - def is_uncategorized object.id == SiteSetting.uncategorized_category_id end @@ -62,4 +37,42 @@ class CategoryDetailedSerializer < BasicCategorySerializer subcategory_ids.present? end + # Topic and post counts, including counts from the sub-categories: + + def topics_day + count_with_subcategories(:topics_day) + end + + def topics_week + count_with_subcategories(:topics_week) + end + + def topics_month + count_with_subcategories(:topics_month) + end + + def topics_year + count_with_subcategories(:topics_year) + end + + def posts_day + count_with_subcategories(:posts_day) + end + + def posts_week + count_with_subcategories(:posts_week) + end + + def posts_month + count_with_subcategories(:posts_month) + end + + def posts_year + count_with_subcategories(:posts_year) + end + + def count_with_subcategories(method) + object.subcategories.inject(object.send(method) || 0) { |sum,c| sum += c.send(method) } + end + end