2011-11-24 73 views
6

我需要創建一些工廠是由多個有許多通過的工廠的女孩多的has_many是

這裏是我的模型

Topic 
    has_many :plan_topics 
    has_many :plans, :through => :plan_topics 

PlanTopic 
    belongs_to :plan 
    belongs_to :topic 

Plan 
    has_many :subscriptions 
    has_many :members, :through => :subscriptions 
    has_many :plan_topics 
    has_many :topics, :through => :plan_topics 

Subscription 
    belongs_to :member 
    belongs_to :plan 

Member 
    has_many :subscriptions 
    has_many :plans, :through => :subscriptions 

這裏是我有什麼

Factory.define :topic do |topic| 
    topic.name "Operations" 
end 

Factory.define :plan do |plan| 
    plan.title "A test Finance plan" 
    plan.price "200" 
end 

Factory.define :plan_topic do |plan_topic| 
    plan_topic.topic {|topic| topic.association(:topic)} 
    plan_topic.plan {|plan| plan.association(:plan)} 
end 

什麼我想要做的是 - 工廠(:member_with_subscription)

Factory.define :member_with_subscription do |subscription| 
    subscription.association(:plan_with_topic) 
    subscription.association(:member) 
end 

有沒有辦法做到這一點?

回答

10

考慮使用after_build回調來設置所有必需的依賴關係。例如:

Factory.define :member_with_subscription, :class => 'Member' do |m| 
    m.after_build do |member| 
    member.subscriptions << Factory.build(:subscription) 
    end 
end 
+0

歡呼聲,那是偉大的! – Alex

6

我這樣做略有不同,而這樣可能會稍微容易理解:

FactoryGirl.define do 
    factory :member_with_description do 
    after(:build) do |member| 
     member.subscriptions << FactoryGirl.build(:subscription) 
    end 
    end 
end 
+0

這是一個很好的例子。謝謝! – MBHNYC