ruby-on-rails – ruby​​数组何时计数不等于数组中的元素数?

我正在运行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">

最佳答案 这可能发生如下:

> @document对象以0 document_items开头.
>直接创建了两个DocumentItem对象,即不通过@ document.document_items关联创建.

如果此时不重新加载@document,则length仅返回内存中为@document对象缓存的document_items数组的大小,该值为0.但是,count将转到数据库,并按预期返回2.

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

点赞