2014-02-25 26 views
0

我已經建立了這樣的情侶款:.first如何在Rails的CollectionProxy上工作?

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 

這是怎麼回事?

+1

嘗試重新加載從DB合同。 – sevenseacat

回答

2

嘗試調用contract.reload

當你調用let變量/方法的價值,也是第一次被調用後緩存。因此,當您撥打contract.invoices.first時,您正調用invoices緩存目前在內存中的contract對象。