Rails急切加载计数?

使用include属性可以很好地加载

Post.find(:all, :include => :author) 

我想知道你是否也可以急切加载计数,比如我想获得每个post的评论数量,而不加载所有评论本身?

也许是这样的

 Post.find(:all, :include => [:author, "count(comments)") 

我想我可以使用count_cache列。 但如果有可能的话,在一个包含中做这一切真的很美。

额外的奖励积分,如果有人可以展示如何不仅得到计数,但也提出一些条件,如只有已经批准的post的数量。

至少在MySQL中,以两个单独的调用来执行这些操作会更快,因为您可以避免连接。 我知道这不能回答你的问题,但似乎你正在努力提高速度和做法

 Post.find ... 

然后

 post.comments.count 

比在一个查询中检索两者的速度更快,内存效率更高(对于数据库)。

他们应该已经加载使用

 post.comments.length 

我遇到了同样的问题,因为我使用的是.count

建立avaynshtok的答案,以下技术应该只进行2次数据库调用。

 # ./app/controllers/posts_controller.rb def index # First load the posts @posts = Post.all # Then you can load a hash of author counts grouped by post_id # Rails 4 version: @comment_counts = Comment.group(:post_id).count # Rails 3 version: # @comment_counts = Comment.count(:group => :post_id) end 

然后在你看来

  <% @posts.each do |post| %>  post_count: <%= @comment_counts[post.id] %> <% end %> 

试试这个:

 Comment.count(:group => :post) 

按条件过滤:

 Comment.count(:group => :post, :conditions => {:approved => true }) 

这些将返回哈希,其中post为关键字,注释数量为值。

我刚刚遇到这个挑战并以这种方式解决了它:

 def trainee_counts @trainee_counts ||= Hash[Trainee.group(:klass_id).count] end # where the count is needed trainee_counts[klass_id].to_i 

一次调用数据库,不加载受训者。