开发者

Ruby 1.92 in Rails 3: A Case where Array.length Does Not Equal Array.count?

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(:f开发者_如何学编程amily)   # 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜