Поиск элемента массива по id в Rails - PullRequest
0 голосов
/ 04 октября 2010

Я новичок в Rails (из PHP). Итак, прости этот вопрос об основных структурах данных:

В контроллере:

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

По виду:

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

При переборе @games вместо отображения идентификатора игрока с помощью game.player_id я хотел бы отобразить имя игрока, которое можно найти в объекте Player (: name).

Как «найти» правильную запись игрока по идентификатору, сохраненному в game.player_id?

1 Ответ

4 голосов
/ 04 октября 2010

В контроллере:

@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%>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...