user1769426
user1769426

Reputation: 117

Rails Model Relationships

If I have a model that has two references to the same model, how do I set it up? What I have right now is

class Game < ActiveRecord::Base
    has_one :home_team_stats, :class_name => 'Stats'
    has_one :away_team_stats, :class_name => 'Stats'

class Stats < ActiveRecord::Base
    belongs_to :game

However, when Activerecord runs the query it searches for the first Stats entry with a game_id of x. Therefore, if the home_stats is latest entry, both the home_stats and away_stats are set to the the home_stats entry. If it was away_game, they'd both be set to that.

Stats Load (0.3ms)  SELECT "stats".* FROM "stats" WHERE "stats"."game_id" = 1 LIMIT 1

From my understanding, the way around this is to change the relationship from a has_one to a belongs_to or something similar. That feels inherently wrong though, as colloquially I'd say the stats belong to a game, and a game has stats for a home team and an away team. Is there a better way to set this up?

EDIT: Figured it out.

I changed the Game Model to the following:

has_one :home_team_stats, :class_name => 'Stats', :foreign_key => "id", :primary_key => "home_team_stats_id"
has_one :away_team_stats, :class_name => 'Stats', :foreign_key => "id", :primary_key => "away_team_stats_id"

Upvotes: 0

Views: 307

Answers (1)

Shane
Shane

Reputation: 514

The problem is that there is no way to identify an instance of Stats as home or away. (That you have shown)

A potential fix is to introduce a home column to stats, then change the relationships to:

class Game < ActiveRecord::Base
  has_one :home_team_stats, :class_name => 'Stats', :conditions => {:home => true}
  has_one :away_team_stats, :class_name => 'Stats', :conditions => {:home => false}

Upvotes: 2

Related Questions