ruby数组何时计数不等于数组中的元素数?

时间:2011-05-06 09:22:03

标签: ruby-on-rails ruby arrays machinist

我正在运行testunit(使用机械师)并且在运行ruby调试器时得到这个非常奇怪的结果

(rdb:1) @document.document_items
[]
(rdb:1) @document.document_items.count
2
(rdb:1) @document.document_items.length
0
(rdb:1) @document.document_items.size
0
(rdb:1) @document.document_items.class
Array
(rdb:1) @document
#<Document id: 1, title: "Recusandae quibusdam dicta deleniti et voluptate.", state: "published", site_id: nil, template_document_id: 2, most_important_message: "Quam totam corporis similique voluptatibus quaerat ...", delta: nil, approver_id: 1, author_id: 1, account_id: 1, updated_at: "2011-05-06 08:59:12", created_at: "2011-05-06 08:59:12">
(rdb:1) DocumentItem.find(:all)
[#<DocumentItem id: 1, title: "Et voluptatem officia voluptatem omnis voluptas.", body: "Nobis iste nostrum beatae corrupti ea qui debitis. ...", position: nil, document_id: 1, created_at: "2011-05-06 08:59:12", updated_at: "2011-05-06 08:59:12", version: 1, is_heading: false, help_message: nil, optional: nil, template_question_id: nil>, #<DocumentItem id: 2, title: "Ipsum in odio laborum ut officia.", body: "Quas temporibus iusto quidem non repellat. Quia des...", position: nil, document_id: 1, created_at: "2011-05-06 08:59:12", updated_at: "2011-05-06 08:59:12", version: 1, is_heading: false, help_message: nil, optional: nil, template_question_id: nil>]

我的Document / DocumentItem模型的片段:

class Document < ActiveRecord::Base
    ...
    has_many :document_items
    ...
end

class DocumentItem < ActiveRecord::Base
    ...
    belongs_to :document
    ...
end

为什么document_items数组的数量与document_items中的元素数量不同?它是某种机械师的魔法吗? (可能与:Ruby 1.92 in Rails 3: A Case where Array.length Does Not Equal Array.count?

有关

但问题在于,为什么document_items为空呢?正确设置了连接,因为它可以正常工作:

(rdb:1) DocumentItem.first.document
#<Document id: 1, title: "Recusandae quibusdam dicta deleniti et voluptate.", state: "published", site_id: nil, template_document_id: 2, most_important_message: "Quam totam corporis similique voluptatibus quaerat ...", delta: nil, approver_id: 1, author_id: 1, account_id: 1, updated_at: "2011-05-06 08:59:12", created_at: "2011-05-06 08:59:12">

1 个答案:

答案 0 :(得分:2)

这可能发生如下:

  1. @document对象以0 document_items开始。
  2. 直接创建了两个DocumentItem个对象,即不通过@document.document_items关联。
  3. 如果此时没有重新加载@document,则length仅返回内存中为@document对象缓存的document_items数组的大小,即0。但是,{ {1}}转到数据库,并按预期返回2.

    为了解决这个问题,您需要在创建新的count对象后在reload上显式调用@document