Ruby 1.92 in Rails 3: Case when Array.length is not equal to Array.count?

I understand that count and length should return the same number for Ruby arrays. So I can’t understand what’s going on here (FactoryGirl is set up to create - save the 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, although I expected f.members to include a database search for members with family_id=f.id and will return all members, even if f is deprecated.

But how can the bill differ from the length? f.members is an Array, but is the count method overridden somewhere, or does Array.count actually return a different result from Array.length? Not a real problem, just a secret that may indicate a major flaw in my understanding of Ruby or Rails.

0
source share
1 answer

When viewing the source https://github.com/rails/rails/blob/master/activerecord/lib/active_record/associations/collection_association.rb, the length calls the size method in the internal collection, and the count actually causes the count in the database.

+5
source

All Articles