与Arel(Rails 3)的加载关联计数

简单的任务:鉴于文章有很多评论,能够在很长的文章列表中显示每篇文章有多少评论。 我正在尝试研究如何使用Arel预加载此数据。

README文件的“复杂聚合”部分似乎讨论了这种情况,但它并不完全提供示例代码,也没有提供在两个查询而不是一个连接查询中执行此操作的方法,这对于性能。

鉴于以下内容:

class Article has_many :comments end class Comment belongs_to :article end 

我如何预装文章设置每个评论有多少?

你可以使用SQL做一些讨厌的事情:

 default_scope :select => 'articles.*, (select count(comments.id) from comments where comments.article_id = articles.id) as count_comments' 

然后您就可以访问Article.first.count_comments。

另一种(更好的)方法是使用belongs_to关联中的’counter_cache’function/选项。

你不能用这个计数器缓存吗?

 belongs_to :article, :counter_cache => true 

您还需要进行添加列comments_count的迁移