Rails 中的大小、长度和数量 [英] size, length and count in Rails

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

问题描述

1.9.3p194 :002 > u = User.find_by_email("email@mail.ru")
1.9.3p194 :005 > u.addresses.size
 => 1 
1.9.3p194 :006 > u.addresses.length
 => 1 
1.9.3p194 :007 > u.addresses.count 

Rails 3.2.3 中的大小、长度和数量没有区别,不是吗?

There is no difference between size, length and count in Rails 3.2.3, isn't it?

推荐答案

length 将加载您所有的对象只是为了计算它们;类似:

length will load all your objects just to count them; something like:

select * from addresses...

然后返回结果计数.你可以想象 - 这是糟糕的表现

and then return the results count. As you can imagine - it's bad performance

count 只会发出

select count(*) from addresses...

哪个更好,因为我们不加载所有地址只是为了计算它们

which is better, because we are not loading all addresses just to count them

size 更智能 - 它会检查关联是否已加载,如果为 true,则返回长度(不调用数据库).

size is smarter - it'll check if the association is already loaded and if true then return the length (without issuing a call to the database).

size 还会检查 counter_cache 如果您的用户模型中有一个名为 address_count 的字段,则 size 将使用此字段进行计数,因此无需对地址表进行计数.

size also checks for counter_cache if you have a field named address_count in your user model, then size will use this field for the count, so there is no need to issue a count on the addresses table.

如果都失败了,size会在数据库上发出一个select count(*)

if all fails, size will issue a select count(*) on the database

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

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