Rails SQL COUNT N+1 inefficiency
You can use counter cache: http://guides.rubyonrails.org/association_basics.html#counter_cache
"With this declaration, Rails will keep the cache value up to date, and then return that value in response to the size method."
class BlogPost < ActiveRecord::Base
has_many :blog_comments
end
class BlogComment < ActiveRecord::Base
belongs_to :blog_post, :counter_cache => true
end
Blog post would have a column named blog_comments_count
.
In general, you want a SQL query like:
SELECT COUNT(*), blog_post_id
FROM blog_comments
GROUP BY blog_post_id;
You can use this to create a hash from blog_post_id to the count of comments.
You can also see something like this:
BlogComment.group('blog_post_id').count
In purely Rails Way. :)