.first如何在Rails中的CollectionProxy上工作?

时间:2014-02-25 02:11:56

标签: ruby-on-rails activerecord ruby-on-rails-4

我有几个模型设置如下:

class Contract < ActiveRecord::Base
  has_many :invoices, dependent: :destroy
end

class Invoice < ActiveRecord::Base
  belongs_to :contract
end

我有一个像这样设置的功能测试...

feature "Some cool functionality", js: true do
  let(:contract) { create(:contract) }
  let(:invoice) { create(:invoice, contract: contract) }

  #etc...
end

在调试测试时我发现了这个......

(byebug) p contract
#<Contract id: 1, created_at: "2014-02-25 01:52:52", updated_at: "2014-02-25 01:52:52">
(byebug) p invoice
#<Invoice id: 1, contract_id: 1, created_at: "2014-02-25 01:52:52", updated_at: "2014-02-25 01:52:52">

这是令人困惑的部分:

(byebug) p contract.invoices.first
nil

我认为这会返回我在功能测试中定义的invoice

但是,我想我可以验证contract有一个invoice ...

(byebug) p contract.invoices.count
   (1.0ms)  SELECT COUNT(*) FROM "invoices" WHERE "invoices"."contract_id" = $1  [["contract_id", 1]]
1

这里发生了什么?

2 个答案:

答案 0 :(得分:2)

尝试拨打contract.reload

当您调用let时,变量/方法的值在第一次调用后被缓存。因此,当您调用contract.invoices.first时,您正在当前内存中的缓存invoices对象上调用contract

答案 1 :(得分:1)

为确保您使用的是最新数据,请尝试使用Rails'reload! console method

# from command line
reload!