ActiveRecord的:大小VS计数 [英] ActiveRecord: size vs count

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

问题描述

在Rails中,你可以找到的记录同时使用 Model.size Model.count 的数量。如果你要处理更复杂的查询是没有任何优势,使用一种方法比其他?他们是如何不同?

In Rails, you can find the number of records using both Model.size and Model.count. If you're dealing with more complex queries is there any advantage to using one method over the other? How are they different?

例如,我有用户的照片。如果我想向用户展示了一个表,他们有多少照片都将运行 user.photos.size 的许多情况下比更快或更慢user.photos.count

For instance, I have users with photos. If I want to show a table of users and how many photos they have, will running many instances of user.photos.size be faster or slower than user.photos.count?

谢谢!

推荐答案

您应该阅读<一个href="http://web.archive.org/web/20100210204319/http://blog.hasmanythrough.com/2008/2/27/count-length-size">that,它仍然是有效的。

You should read that, it's still valid.

您会适应你请根据您的需要的功能。

You'll adapt the function you use depending on your needs.

基本上是:

  • 如果你已经装载的所有条目,比如 User.all ,那么你应该使用长度来避免另一个数据库查询

  • if you already load all entries, say User.all, then you should use length to avoid another db query

如果您有没有什么装,使用计数来进行计数查询您的分贝

if you haven't anything loaded, use count to make a count query on your db

如果你不想理会这些考虑,使用尺寸将调整

if you don't want to bother with these considerations, use size which will adapt

这篇关于ActiveRecord的:大小VS计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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