2010-04-08 56 views
3

简单的任务:鉴于文章有很多评论,能够在一长串文章中显示每篇文章有多少评论。我正在努力解决如何使用Arel预加载这些数据。与Arel(Rails 3)的急切加载关联计数

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

考虑以下几点:

class Article 
    has_many :comments 
end 

class Comment 
    belongs_to :article 
end 

我如何可以预载的一篇文章设置多少意见各有?

回答

2

可以使用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'特性/选项。

+0

傻我在匆忙,忘了有关缓存吧:)谢谢! – Matchu 2010-04-11 21:28:58

4

你不能使用计数器缓存吗?

belongs_to :article, :counter_cache => true 

您还需要有一个迁移,增加了列comments_count

+0

我最近在生产中遇到了使用counter_cache单表继承的问题,不得不自己推出 – nurettin 2012-12-10 12:08:56