在Rails中通过id查找数组元素

时间:2010-10-04 05:14:10

标签: ruby-on-rails

我是Rails新手(来自PHP)。所以原谅这个基本的数据结构问题:

在控制器中:

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

在视图中:

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

当迭代@games,而不是用game.player_id显示玩家ID时,我想显示玩家的名字,可以在玩家对象(:名称)中找到。

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

1 个答案:

答案 0 :(得分: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

如果您有团队概念,我将介绍团队模型:

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%>