红宝石1.92 Rails中3:的情况下Array.length不等于Array.count? [英] Ruby 1.92 in Rails 3: A Case where Array.length Does Not Equal Array.count?

查看:297
本文介绍了红宝石1.92 Rails中3:的情况下Array.length不等于Array.count?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的理解是,计数长度应该返回相同的数字为Ruby阵列。所以,我想不出什么是怎么回事(FactoryGirl设置为创建 - 保存到数据库 - 默认情况下):

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]

我隐约明白为什么˚F需要重新加载,但我本来期望 f.members 将涉及数据库查找会员与 family_id = f.id ,并且将返回所有成员即使f是陈旧的。

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.

但如何才能计数是从长度不同? f.members是一个数组,但是是计数方法被覆盖的地方,或者是Array.count实际上返回从Array.length不同的结果?不是pressing问题,只是一个谜,可能表明我的Ruby或者Rails的理解基本的缺陷。

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.

推荐答案

在查看源,<一个href="https://github.com/rails/rails/blob/master/activerecord/lib/active_record/associations/collection_association.rb">https://github.com/rails/rails/blob/master/activerecord/lib/active_record/associations/collection_association.rb,长呼吁内部集合大小的方法和计算实际调用数在数据库中。

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.

这篇关于红宝石1.92 Rails中3:的情况下Array.length不等于Array.count?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆