2012-03-16 96 views
0

我有兩個factory_girl工廠,contactuser。聯繫有一個屬性,dest_user_id,這是一個外鍵user,但可以爲NULL。對於該屬性,我想創建一個使用user工廠的新用戶,然後將其ID分配給dest_user_id。有沒有辦法做到這一點?在工廠定義中,使用其他工廠的屬性分配屬性

+0

。這兩個型號之間的關聯的名稱超過dest_user_id轉讓的控制,描述了dest_user_id?爲了清晰起見,請張貼模型細節。 – nmott 2012-03-17 12:41:24

+0

我加了一個事實,即dest_user_id是一個外鍵。這有什麼關係?對於user的任何屬性,問題都是一樣的。 – FrontierPsycho 2012-03-17 14:29:50

+0

只是想確保你沒有改變關係名稱和外鍵名稱,因爲它會稍微改變潛在的解決方案。可能的做法如下。 – nmott 2012-03-18 12:55:24

回答

0

如果與dest_user_id的外鍵保持與型號名稱相同,則不應改變方法。假設contactbelongs_touseruser要麼has_onehas_manycontacts,你可以達到你想要的東西如下:

首先創建工廠:

FactoryGirl.define do 
    factory :user do 
    Field 1 
    Field 2 
    # etc 
    end 

    factory :contact do 
    # Add only the minimum fields required to create a contact, but not the association 
    Field 1 
    Field 2 

    factory :contact_with_user do 
     # then you add the association for this inherited factory 
     # we can use 'user' here as the factory is the same as the association name 
     user 
    end 
    end 
end 

使用此設置創建一個contact沒有user,因此dest_user_idNULL當用戶FactoryGirl.create(:contact)測試/規格內。

要創建user和ID分配到dest_user_id田野上contact你可以使用下列內容:

@user = FactoryGirl.create(:user) 
@contact = FactoryGirl.create(:contact_with_user, :user => @user) 

這種方法最大的靈活性,你可以使用或不使用用戶創建一個contact,和你只有在您需要進行特定測試時,纔可以將user.id傳遞到聯繫人模型。如果你打電話FactoryGirl.create(:contact_with_user)然後既是contactuser將自動創建,但你不會有,你有當您使用FactoryGirl.create(:contact_with_user, :user => @user)

相關問題