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

拜拜、爱过 提交于 2020-01-06 14:17:14

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/5434624/ruby-1-92-in-rails-3-a-case-where-array-length-does-not-equal-array-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!