2010-10-04 51 views
0

我是Rails的新手(来自PHP)。所以请原谅这个基本的数据结构问题:在Rails中通过id查找数组元素

在控制器:

@games = Game.all 
@players = Player.all 

在视图:

<% @games.each do |game| %> 
    <%= game.player_id %> 
<% end %> 

当遍历@games,而不是与游戏显示玩家ID。 player_id,我想显示可以在Player对象(:name)中找到的播放器名称。

如何通过存储在game.player_id中的id找到正确的玩家记录?

回答

4

在控制器:

@games = Game.all(:include => :player) 

在视图:

<% @games.each do |game| %> 
    <%= game.player.name %>  
<% end %> 

你的数据模型看起来很奇怪我。对于类似的问题,我的数据模型可能是这样的:

class Game < ActiveRecord::Base 
    has_many :game_players 
    has_many :players, :through => :game_players 
end 

class GamePlayer < ActiveRecord::Base 
    belongs_to :game 
    belongs_to :player 
end 

class Player < ActiveRecord::Base 
    has_many :game_players 
    has_many :games, :through => :game_players 
end 

现在在控制器中我将查询游戏:

@games = Game.all(:include => :players) 

在视图:

<%@games.each do |game| %> 
    <% games.players.each do |player| %> 
    <%= player.name %> 
    <%end%> 
<%end%> 

编辑1

如果你有一个团队的概念,那么我将我ntroduce组队模式:

class Player < ActiveRecord::Base 
    has_many :team_players 
    has_many :teams, :through => :team_players 
end 

class TeamPlayer < ActiveRecord::Base 
    belongs_to :player 
    belongs_to :team 
end 

class Team < ActiveRecord::Base 
    has_many :team_players 
    has_many :players, :through => :team_players 
    belongs_to :game 
    # attributes name, score team size constraints etc. 
end 

class Game 
    has_many :teams 
    has_many :players, :through => :teams. 
end 

添加新的游戏:

@game = Game.new 

@team_a = @game.teams.build(:name => "Foo") 
@team_a.players << Player.find_all_by_name(["John", "Grace"]) 

@team_b = @game.teams.build((:name => "Bar") 
@team_b.players << Player.find_all_by_name(["Kelly", "Yuvan"]) 

@game.save 

在查询时在你的控制器的游戏:

@games = Game.all(:include => [{:teams => :players}]) 

在你看来:

<%@games.each do |game| %> 
    <% games.teams.each do |team| %> 
    <% team.players.each do |team| %> 
     <%= player.name %> 
    <%end%> 
    <%end%> 
<%end%> 
+0

谢谢花时间查看我的数据模型。你将如何限制球员在比赛中的某些位置?如果是双打网球比赛,每个球队都有两名球员互相比赛。这场比赛将为每支球队打分。 – Etienne 2010-10-04 14:13:46

+0

更新了答案,看看。 – 2010-10-04 15:28:12

+0

太棒了。最后一个Rails相关的问题。考虑到我用我的模型和相关的迁移走了错误的道路,如何重做?我是否只是创建一个新的迁移来修复架构以支持新模型,还是删除现有迁移并创建新迁移? – Etienne 2010-10-04 19:06:57