Rails 急切加载计数? [英] Rails eager loading of counts?

查看:44
本文介绍了Rails 急切加载计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 include 属性可以快速加载

Eager loading is nice with the include attribute

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

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

I'm wondering if you can also eager load counts, like if I wanted to get the number of comments for each post, without loading all the comments themselves?

也许类似

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

我想我可以使用 count_cache 列.但是如果可能的话,在一个包含中完成这一切会非常漂亮.

I suppose I could use a count_cache column. But doing it all in an include would be really beautiful, if it's possible.

如果有人不仅可以展示如何获得计数,还可以设置一些条件,例如仅对已批准的帖子计数.

Extra bonus points if someone can show how to not only get the count, but put some conditions too, like count of only posts which have been approved.

推荐答案

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

In MySQL at least, it is faster to do these as two separate calls because you get to avoid the join. I know this doesn't answer your question, but it seems like you're trying to get better speed and doing

Post.find ...

然后

post.comments.count

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

Is faster and more memory efficient (for the database) than if you retrieve both in one query.

这篇关于Rails 急切加载计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆