2010-03-02 6 views
9

나는 공장 소녀를 만난다. 어려움에 처하게되고 훨씬 쉬워진다. 문서를 실제 예제로 만들 수는 없습니다.공장 아가씨 : 자동으로 상위 개체 할당

class League < ActiveRecord::Base 
    has_many :teams 
end 

class Team < ActiveRecord::Base 
    belongs_to :league 
    has_many :players 
end 

class Player < ActiveRecord::Base 
    belongs_to :team 
end 

내가하고 싶은 것은 이것이다 :

나는 다음과 같은 모델을 가지고 가정

team = Factory.build(:team_with_players) 

과 나를 위해 선수의 무리를 구축해야합니다. 나는이 시도 :

Factory.define :team_with_players, :class => :team do |t| 
    t.sequence {|n| "team-#{n}" } 
    t.players {|p| 
     25.times {Factory.build(:player, :team => t)} 
    } 
end 

을하지만 tTeam이, 그것은 Factory::Proxy::Builder의 정말하지 않기 때문에 이것은 :team=>t 섹션에 실패합니다. I 팀이 플레이어에게 배정되도록해야합니다.

어떤 경우에는 League을 빌드하고 여러 플레이어가있는 여러 팀을 만드는 유사한 작업을 수행하려고합니다.

무엇이 누락 되었습니까? 이것에 대해

+0

난 그냥이 동일한 문제 (같은 오류)로 실행하고 모든 주위를 둘러 보았다 및 해결책을 발견하지 않았습니다. –

답변

5
Factory.define :team do |team| 
    team.sequence(:caption) {|n| "Team #{n}" } 
end 

Factory.define :player do |player| 
    player.sequence(:name) {|n| "John Doe #{n}" } 
    player.team = nil 
end 

Factory.define :team_with_players, :parent => :team do |team| 
    team.after_create { |t| 25.times { Factory.build(:player, :team => t) } } 
end 
2

방법은 :

Factory.define :team_with_players, :class => :team do |t| 
    t.sequence { |n| "team-#{n}" } 
    t.players do |team| 
    25.times.collect { |n| team.association(:player) } 
    end 
end 
+0

그러나 플레이어가 팀에 대한 참조가 필요하면 어디서 구할 수 있습니까? 이 예제에서 "팀"은 팩토리 객체를 참조합니다. –

+0

다음과 비슷한 점이 있습니다. team.association (: player, : team_id => team)이 이상하게 보이지만 저에게 효과적입니다. – Priit

+1

내가 그렇게 할 때 : "예상 팀,하지만 FactoryGirl : : Proxy"또는 이와 비슷한 것입니다. –