From eb56521a66863abf8ab78db41883cf8c4c1aa964 Mon Sep 17 00:00:00 2001
From: Raphael <raphael@joindiaspora.com>
Date: Thu, 16 Dec 2010 12:25:31 -0800
Subject: [PATCH] Don't query inside of loops...

---
 app/controllers/aspects_controller.rb       | 16 ++++++++++++----
 spec/controllers/aspects_controller_spec.rb |  2 +-
 2 files changed, 13 insertions(+), 5 deletions(-)

diff --git a/app/controllers/aspects_controller.rb b/app/controllers/aspects_controller.rb
index 39ec4c3b7e..3a436dc48c 100644
--- a/app/controllers/aspects_controller.rb
+++ b/app/controllers/aspects_controller.rb
@@ -192,18 +192,26 @@ class AspectsController < ApplicationController
     end
   end
   def hashes_for_posts posts
-    post_ids = posts.map{|p| p.id}
+    post_ids = []
+    post_person_ids = []
+    posts.each{|p| post_ids << p.id; post_person_ids << p.person_id}
+
     comment_hash = Comment.hash_from_post_ids post_ids
-    person_hash = Person.from_post_comment_hash comment_hash
+    commenters_hash = Person.from_post_comment_hash comment_hash
     photo_hash = Photo.hash_from_post_ids post_ids
 
+    post_person_ids.uniq!
+    posters = Person.all(:id.in => post_person_ids, :fields => [:profile, :owner_id])
+    posters_hash = {}
+    posters.each{|poster| posters_hash[poster.id] = poster}
+
     posts.map do |post|
       {:post => post,
         :photos => photo_hash[post.id],
-        :person => post.person,
+        :person => posters_hash[post.person_id],
         :comments => comment_hash[post.id].map do |comment|
           {:comment => comment,
-            :person => person_hash[comment.person_id],
+            :person => commenters_hash[comment.person_id],
           }
         end,
       }
diff --git a/spec/controllers/aspects_controller_spec.rb b/spec/controllers/aspects_controller_spec.rb
index d473f05475..028e8402d4 100644
--- a/spec/controllers/aspects_controller_spec.rb
+++ b/spec/controllers/aspects_controller_spec.rb
@@ -54,7 +54,7 @@ describe AspectsController do
       it 'takes time' do
         Benchmark.realtime{
           get :index
-        }.should < 2
+        }.should < 1.5
       end
     end
   end
-- 
GitLab