2013-11-03 142 views
2

我在FactoryGirl中建立了一個非常簡單的關聯,但是由於某種原因它沒有工作。該應用程序適用於旅遊公司,因此每個遊覽都有一個目的地(我使用的是ActiveRecord,因此Tour型號belongs_to a Destination - 此關聯是所有遊覽所必需的)。所以,我建立了我的工廠是這樣的:工廠女孩協會不工作

# spec/factories.rb 
FactoryGirl.define do 

    factory :destination do 
    name "Example Destination" 
    city "Example City" 
    state "CA" 
    end 

    factory :tour do 
    departure_date { 1.day.from_now } 
    return_date { 1.day.from_now } 
    destination 
    end 
end 

然而,當我打電話FactoryGirl.attributes_for(:tour),它返回:

{:departure_date => Mon, 04 Nov 2013 17:51:26 UTC +00:00, 
:return_date => Mon, 04 Nov 2013 17:51:26 UTC +00:00} 

沒有destination_id!爲什麼?

destination工廠工作得很好。

我試圖定義關聯的舊方式association :destination, factory: :destination,但這並沒有幫助。如果我手動將destination_id定義爲destination_id FactoryGirl.create(:destination).id,那麼我可以使它工作,但我不應該那樣做。任何想法爲什麼它不工作?

+0

爲什麼不'目的地nil',如果你不希望任何分配原來。 – tolgap

+0

我確實要分配目標 - 所有'tours'都需要'destination_id' –

回答

4

attributes_for不會加載關聯的對象。它只爲您請求的對象生成屬性。

要使其加載關聯的destination,請改爲使用buildcreate

1

這些attributes_for不創建關聯屬性(我相信設計)。這應該工作:

FactoryGirl.attributes_for(:tour, :destination_attributes => FactoryGirl.attributes_for(:destination)) 

但是,這可能是一個滑頭的解決方案:

https://stackoverflow.com/a/10294322/632735

:)

+0

我的'tour'模型需要接受'destination'的嵌套屬性嗎?因爲它不適合我(「unknown attribute:destination_attributes」)。儘管感謝您的鏈接!很有幫助。如果你編輯答案,我會給你一個upvote –

+0

你有Tourtr模型中的attr_accessible:destination_attributes嗎?這應該排序:) –

+0

這個問題是'attributes_for'不會持續記錄,因此'destination_id'永遠不會生成。 –