From d6ca23a75b3501e4fff40eb81bc802828faea07d Mon Sep 17 00:00:00 2001 From: Sam Date: Fri, 8 Mar 2013 05:34:19 -0800 Subject: [PATCH] remove N+1 queries --- app/models/category.rb | 6 +++++- app/models/site.rb | 2 +- lib/topic_query.rb | 2 +- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/app/models/category.rb b/app/models/category.rb index c1643c68aa5..f55aaa786b4 100644 --- a/app/models/category.rb +++ b/app/models/category.rb @@ -1,5 +1,9 @@ class Category < ActiveRecord::Base belongs_to :topic, dependent: :destroy + belongs_to :topic_only_relative_url, + select: "id, title", + class_name: "Topic", + foreign_key: "topic_id" belongs_to :user has_many :topics @@ -43,7 +47,7 @@ class Category < ActiveRecord::Base end def topic_url - topic.try(:relative_url) + topic_only_relative_url.try(:relative_url) end before_save do diff --git a/app/models/site.rb b/app/models/site.rb index 1d63ae46eb5..f4c4f9f3125 100644 --- a/app/models/site.rb +++ b/app/models/site.rb @@ -22,7 +22,7 @@ class Site end def categories - Category.popular + Category.popular.includes(:topic_only_relative_url) end def archetypes diff --git a/lib/topic_query.rb b/lib/topic_query.rb index f6a75dcaaf6..86fecc981ca 100644 --- a/lib/topic_query.rb +++ b/lib/topic_query.rb @@ -196,7 +196,7 @@ class TopicQuery end end - result = result.listable_topics.includes(:category) + result = result.listable_topics.includes(:category => :topic_only_relative_url) result = result.where('categories.name is null or categories.name <> ?', query_opts[:exclude_category]) if query_opts[:exclude_category] result = result.where('categories.name = ?', query_opts[:only_category]) if query_opts[:only_category] result = result.limit(page_size) unless query_opts[:limit] == false