cache reply_to_user_id in post to eliminate a very nasty n+1 query

This commit is contained in:
Sam
2013-03-19 16:51:39 -07:00
parent ec948dc660
commit 2a047df4f1
4 changed files with 34 additions and 9 deletions

View File

@@ -0,0 +1,16 @@
class AddReplyToUserIdToPost < ActiveRecord::Migration
def up
# caching this column makes the topic page WAY faster
add_column :posts, :reply_to_user_id, :integer
execute 'UPDATE posts p SET reply_to_user_id = (
SELECT u.id from users u
JOIN posts p2 ON p2.user_id = u.id AND
p2.post_number = p.reply_to_post_number AND
p2.topic_id = p.topic_id
)'
end
def down
remove_column :posts, :reply_to_user_id
end
end