ActiveRecord:大小与数量 [英] ActiveRecord: size vs count

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

问题描述

在 Rails 中,您可以使用 Model.sizeModel.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?

谢谢!

推荐答案

您应该阅读 ,它仍然有效.

You should read that, it's still valid.

您将根据需要调整使用的功能.

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

基本上:

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

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

如果你还没有加载任何东西,使用 count 对你的数据库进行计数查询

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

如果您不想为这些考虑而烦恼,请使用 size 这将适应

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

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

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