Eager-loading association count with Arel (Rails 3)

Posted by Matchu on Stack Overflow See other posts from Stack Overflow or by Matchu
Published on 2010-04-08T00:23:23Z Indexed on 2010/04/08 8:43 UTC
Read the original article Hit count: 657

Simple task: given that an article has many comments, be able to display in a long list of articles how many comments each article has. I'm trying to work out how to preload this data with Arel.

The "Complex Aggregations" section of the README file seems to discuss that type of situation, but it doesn't exactly offer sample code, nor does it offer a way to do it in two queries instead of one joined query, which is worse for performance.

Given the following:

class Article
  has_many :comments
end

class Comment
  belongs_to :article
end

How can I preload for an article set how many comments each has?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby-on-rails3