2015-07-19 91 views
0

我有Match模型和我有Player模型。 现在我想添加到Match两个字段,如:playeroneplayertwo。 我想playerone有一个参考具体Player对象和playertwo有一个参考另一个Player对象了。在模型中的两个filelds与参考相同的模型

我是想这样的事情:

rails g model Match player:references 

但这种方式我可以只创建一个域。我无法为此字段创建自定义名称。

或者我可以创建playerone:integer存档并放在这里播放器的id(在控制器中)。但可以吗?

回答

2

如果每场比赛总是只有2名球员,那么可以创建player_one_id:integer和player_two_id:整数场。在匹配模式,你就只能

has_one :player_one, class_name: 'Player', primary_key: :player_one_id 
has_one :player_two, class_name: 'Player', primary_key: :player_two_id 

然后,您可以只设置这些从形式

<%= f.collection_select :player_one_id, Players.all, :id, :name %> 
<%= f.collection_select :player_two_id, Players.all, :id, :name %> 

或者编程

@match.player_one = Player.find(1) 
@match.player_two = Player.find(2) 

该模型的模型CMDLINE发生器会看像这样的东西

rails g model Match player_one_id:integer:index player_two_id:integer:index 
相关问题