我的应用会检索每个帖子的一组标签,但由于某种原因,它会运行重复的查询:
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
让我的代码在视图页面中保持简单:
@posts.each do |post|
# code/html to print out post here
print_tags(post.tags.order('created_at desc'))
end
这是我在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
我不明白为什么它在没有order_by的情况下首先运行查询,然后用它运行查询。性能还不错尚未,但如果它确实为每个帖子运行了两个查询,那么这可能会很快变得难看。
答案 0 :(得分:1)
尝试急切加载您的代码关联:
@posts.includes(:tags).each do |post|
# do something with `post.tags`
end