Forum: Ruby on Rails ActiveRecord: Pointing to two records in one table from a re

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
2ef9c04bdaa45efcd5431d90750c2833?d=identicon&s=25 mrmarkham (Guest)
on 2007-04-10 03:35
(Received via mailing list)
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.

D7c511ce5025d37b8c6bd9134e0f2bd9?d=identicon&s=25 Thorsten (Guest)
on 2007-04-10 10:32
(Received via mailing list)
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.
This topic is locked and can not be replied to.