ActiveRecord: Pointing to two records in one table from a re

I’m relatively new to Rails (well, I got involved in it last fall, but
got away from it) and am trying to figure out a reasonable way to
model the following:


  • id
  • name


  • id
  • first_team_id
  • frist_team_score
  • second_team_id
  • second_team_score

There will be lots of other information, but I was hoping to find an
elegant way to point to two different rows in the team table (ideally
allowing ActiveRecord to help me out) from one row in the game table.

team - has_many :games
game - has_many :teams {:limit => ‘2’}

Gets me somewhat there, but I also need to know things like the scores
for each time. That way I can figure out which team won to determine
things like season records, etc.

It’s a very simplified model, but if someone has a good way to handle
that scenario, I think the rest will fall in place.


something like this:

class Team < ActiveRecord::Base
has_many :games_as_home, :foreign_key => “first_team_id”
has_many :games_as_guest, :foreign_key => “second_team_id”

class Game < ActiveRecord::Base
belongs_to :home_team, :foreign_key => “first_team_id”
belongs_to :guest_team, :foreign_key => “second_team_id”

Then you can e.g. do:

@team = @Team.find(params[:id]
@home_games = @team.games_as_home
@guest_games = @team.games_as_guest
@no_of_games = @home_games.count + @guest_games.count
@home_games_won = @home_games.count :conditions => “first_team_score >
@guest_games_won = @guest_games.count, :conditions =>
“first_team_score < second_team_score”
@tie_games = home_games.count :conditions => “first_team_score =
second_team_score” + @guest_games.count :conditions =>
“first_team_score = second_team_score”

you could encapsulate some of that stuf into a Model method too, if
you need to do those calculations often throughout your app.