Factory Girl:自动分配父对象
我刚刚进入《工厂女孩》,遇到了一个困难,我确信这应该容易得多。我只是无法将文档转变为工作示例。
假设我有以下模型:
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
,它是 <代码>工厂::代理::构建器。我必须为一名玩家分配一个团队。
在某些情况下,我想建立一个联盟并让它做类似的事情,创建多个拥有多个玩家的团队。
我缺少什么?
I'm just getting into Factory Girl and I am running into a difficulty that I'm sure should be much easier. I just couldn't twist the documentation into a working example.
Assume I have the following models:
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
What I want to do is this:
team = Factory.build(:team_with_players)
and have it build up a bunch of players for me. I tried this:
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
But this fails on the :team=>t
section, because t
isn't really a Team
, it's a Factory::Proxy::Builder
. I have to have a team assigned to a player.
In some cases I want to build up a League
and have it do a similar thing, creating multiple teams with multiple players.
What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这个怎么样:
How about this: