Rails 3 中的 Ruby 1.92:Array.length 不等于 Array.count 的情况?

发布于 2024-10-26 05:11:42 字数 875 浏览 1 评论 0原文

我的理解是,对于 Ruby 数组,countlength 应该返回相同的数字。所以我无法弄清楚这里发生了什么(FactoryGirl 默认情况下设置为创建 - 保存到数据库):

f = Factory(:family)   # Also creates one dependent member
f.members.count   # => 1
f.members.length  # => 1
m = Factory(:member, :family=>f, :first_name=>'Sam') #Create a 2nd family member
f.members.count   # => 2
f.members.length  # => 1
puts f.members    # prints a single member, the one created in the first step
f.members.class   # => Array

f.reload
[ Now count == length = 2, and puts f.members prints both members]

我模糊地理解为什么 f 需要重新加载,尽管我预计 f. members 将涉及数据库查找具有 family_id=f.id 的成员,并且即使 f 已过时也会返回所有成员。

但计数与长度怎么会不同呢? f.members 是一个数组,但是 count 方法是否在某处被重写,或者 Array.count 实际上返回了与 Array.length 不同的结果?不是一个紧迫的问题,只是一个谜,可能表明我对 Ruby 或 Rails 的理解存在基本缺陷。

My understanding is that count and length should return the same number for Ruby arrays. So I can't figure out what is going on here (FactoryGirl is set to create--save to database--by default):

f = Factory(:family)   # Also creates one dependent member
f.members.count   # => 1
f.members.length  # => 1
m = Factory(:member, :family=>f, :first_name=>'Sam') #Create a 2nd family member
f.members.count   # => 2
f.members.length  # => 1
puts f.members    # prints a single member, the one created in the first step
f.members.class   # => Array

f.reload
[ Now count == length = 2, and puts f.members prints both members]

I vaguely understand why f needs to be reloaded, though I would have expected that f.members would involve a database lookup for members with family_id=f.id, and would return all the members even if f is stale.

But how can the count be different from the length? f.members is an Array, but is the count method being overridden somewhere, or is the Array.count actually returning a different result from Array.length? Not a pressing issue, just a mystery that might indicate a basic flaw in my understanding of Ruby or Rails.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

人生戏 2024-11-02 05:11:42

在查看源代码时, https://github.com/rails/ Rails/blob/master/activerecord/lib/active_record/associations/collection_association.rb,length 调用内部集合上的 size 方法,而 count 实际上调用数据库上的 count。

In looking at the source, https://github.com/rails/rails/blob/master/activerecord/lib/active_record/associations/collection_association.rb, length calls the size method on the internal collection and count actually calls count on the database.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文