dimanche 22 février 2015

Rails running duplicate queries

My app retrieves a set of tags per post, but for some reason it is running duplicate queries:



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


to keep it simple my code in the view page:



@posts.each do |post|
# code/html to print out post here
print_tags(post.tags.order('created_at desc'))
end


What I don't understand is why it runs a query first without the order_by, and then runs the query with it. Performance isn't bad yet, but if it really is running two queries for each post, then that could get ugly pretty fast.





Aucun commentaire:

Enregistrer un commentaire