Benchmark.measure
1. no join query but 3 times sql call
puts Benchmark.measure { article_ids = Article.onwer_index_all(user_id).collect(&:id) tag_ids = Gutentag::Tagging.where("taggable_type = 'Article'").where(taggable_id: article_ids).collect(&:tag_id) tags = Gutentag::Tag.where(id: tag_ids).order("taggings_count DESC") }0.005433 0.000419 0.005852 ( 0.015028)
2. left join
puts Benchmark.measure { tags = Gutentag::Tag.joins("INNER JOIN gutentag_taggings ON gutentag_tags.id = gutentag_taggings.taggable_id INNER JOIN articles ON gutentag_taggings.taggable_id = articles.id AND gutentag_taggings.taggable_type = 'Article'").where(articles: {user_id: user_id}).all.distinct("gutentag_tags.name") }0.000511 0.000004 0.000515 ( 0.000514)
no join query is 0.015028
left join elapse time is 0.000514
left join is 29 times as fast as 3 times sql call