2011-11-24 12 views
6

tôi cần phải tạo ra một số nhà máy được làm bằng nhiều có nhiều thông qua lànhà máy cô gái nhiều has_many qua là

Dưới đây là mô hình của tôi

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 

Dưới đây là những gì tôi có

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 

gì Tôi muốn làm điều này - Nhà máy (: member_with_subscription)

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

Có cách nào để thực hiện việc này không?

Trả lời

10

Cân nhắc sử dụng after_build gọi lại để đặt tất cả các phụ thuộc bắt buộc. Ví dụ:

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

Chúc mừng, đó là tuyệt vời! – Alex

6

tôi làm điều đó hơi khác nhau, và cách này có thể là một chút dễ dàng hơn để hiểu:

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

Đây là một ví dụ tuyệt vời. Cảm ơn! – MBHNYC