Rails 3 中的 Ruby 1.92:Array.length 不等于 Array.count 的情况?
我的理解是,对于 Ruby 数组,count
和 length
应该返回相同的数字。所以我无法弄清楚这里发生了什么(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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在查看源代码时, 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.