Using Nested Selects for Performance in Rails
blog.aha.io
blog.aha.io
If you EXPLAIN that query, it's a DEPENDENT SUBQUERY which has to fetch N*M records. It would be mitigated if the columns are property indexed, but two separate queries (N+M) just as eager loading would be faster and more predictable than nested scans in terms of IOPS.
Define a relationship:
has_many :approved_comments, class_name: "Comments", condtions: {approved: true}
Then eager load approved_comments.
I wish if we could do something like:
has_one :approved_comments_count, -> { select(:post_id, 'COUNT(comments.post_id) as comment_count').group(:post_id) }, class_name: 'Comment'
and
posts.includes(:approved_comments_count).map(&:comment_count)