News for hackers. Stuff that matters.
Re:Using Nested Selects for Performance in Rails by yarb on Friday July 10, 2015 @02:15AM (#9862527)
"But there is no easy way to do this in ActiveRecord without sacrificing eager loading."

Define a relationship:

has_many :approved_comments, class_name: "Comments", condtions: {approved: true}

Then eager load approved_comments.

Re:Using Nested Selects for Performance in Rails by kenn on Friday July 10, 2015 @04:13AM (#9862805)
That works, but what if there are thousands of comments? Initializing N*M AR objects could be even slower than N+1 queries.

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)