我刚刚进入工厂女孩,我遇到了一个我确信应该更容易的困难。我只是无法将文档扭曲成一个有效的例子。
假设我有以下型号:
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
但:team=>t
部分失败了,因为t
实际上不是Team
,而是Factory::Proxy::Builder
。我 将球队分配给球员。
在某些情况下,我想建立一个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
答案 1 :(得分: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