0
我的應用程序檢索一組的每個職位的標籤,但由於某種原因它正在運行重複查詢:Rails的運行重複查詢
@posts.each do |post|
# code/html to print out post here
print_tags(post.tags.order('created_at desc'))
end
:
Post Load (0.2ms) SELECT `posts`.* FROM `posts` WHERE `posts`.`user_id` = 1
Tag Load (0.2ms) SELECT `tags`.* FROM `tags` INNER JOIN `post_tags` ON `tags`.`id` = `post_tags`.`tag_id` WHERE `post_tags`.`post_id` = 107
Tag Load (0.3ms) SELECT `tags`.* FROM `tags` INNER JOIN `post_tags` ON `tags`.`id` = `post_tags`.`tag_id` WHERE `post_tags`.`post_id` = 107 ORDER BY post_tags.created_at
Tag Load (0.1ms) SELECT `tags`.* FROM `tags` INNER JOIN `post_tags` ON `tags`.`id` = `post_tags`.`tag_id` WHERE `post_tags`.`post_id` = 106
Tag Load (0.2ms) SELECT `tags`.* FROM `tags` INNER JOIN `post_tags` ON `tags`.`id` = `post_tags`.`tag_id` WHERE `post_tags`.`post_id` = 106 ORDER BY post_tags.created_at
Tag Load (0.2ms) SELECT `tags`.* FROM `tags` INNER JOIN `post_tags` ON `tags`.`id` = `post_tags`.`tag_id` WHERE `post_tags`.`post_id` = 105
Tag Load (0.2ms) SELECT `tags`.* FROM `tags` INNER JOIN `post_tags` ON `tags`.`id` = `post_tags`.`tag_id` WHERE `post_tags`.`post_id` = 105 ORDER BY post_tags.created_at
,以保持它的簡單我在視圖頁面代碼
這裏是PostsHelper我的print_tags代碼:
def print_tags(tags)
returnStr = ""
tags.each do |tag|
returnStr += "<span class='tags'><a href='/users/#{@user.id}/tags/#{tag.tag_name.gsub(' ', '-')}'>#{tag.tag_name}</a></span>"
end
returnStr
end
我不明白的是爲什麼它第1W運行一個查詢沒有order_by,然後用它運行查詢。性能還不錯還有,但是如果它真的在爲每個帖子運行兩個查詢,那麼它可能會變得非常快。
我認爲,如果你提供的方法「print_tags」這將是有益的。 我認爲一個更好的做法是將帖子加載爲塊。而不是@ posts.each do | post | ...結束,可能更好的方法是@ posts.include(:tags).order('tags.created_at desc')或類似的東西。可能會導致只有1個數據庫查詢,而不是每個帖子1查詢。 *未經測試的代碼* http://apidock.com/rails/ActiveRecord/QueryMethods/includes – Mingsheng 2015-02-23 06:47:43
您是否在其他地方使用post.tags? – 2015-02-23 07:11:26
是的,我似乎也在某處使用了post.tags.length。儘管使用急切加載似乎解決了這個問題。謝謝! – user3822741 2015-02-23 07:22:35