Reputation: 5288
Im creating a RoR app to manage a basketball league. I have two tables: teams
& games
. Its set up that each team has many games. Each row in games
contains two foreign keys; one for home team, and one for away team. I have the following code to list the data in the games
table:
<% @games.each do |game| %>
<tr>
<td><%= game.home_team_id %></td>
<td><%= game.away_team_id %></td>
<td><%= game.home_team_score %></td>
<td><%= game.away_team_score %></td>
<td><%= game.date %></td>
</tr>
<% end %>
However, the first two parts dont work, presumably because is used the format when calling an objects child. But here, im trying to call the child's parent (game.home_team_id)
How do you get the parent of a child?
Here's my Game model:
class Game < ActiveRecord::Base
belongs_to :team, :foreign_key => "home_team"
belongs_to :team, :foreign_key => "away_team"
has_many :stats
end
Upvotes: 0
Views: 1141
Reputation: 1484
If the column names are as you specified in your view, you should be seeing the IDs.
Typically, in you game model you would do
belongs_to :home_team, :class_name=>"Team"
belongs_to :away_team, :class_name=>"Team"
then in your view, you would do
<td><%= game.home_team.name %></td>
<td><%= game.away_team.name %></td>
If you aren't seeing at the IDs as it is, i would check that the values are being set.
In console, just do:
Game.first.inspect
If the team ids are empty, we have found the source of this error. Which hints at a problem in your create method.
Upvotes: 3