问题描述
在 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
?
谢谢!
推荐答案
你应该阅读 那个,它仍然有效.
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 uselength
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:大小与计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!