title: Rails Model Relationships
body: <p>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 </p>
  
  <pre><code>class Game &lt; ActiveRecord::Base
      has_one :home_team_stats, :class_name =&gt; 'Stats'
      has_one :away_team_stats, :class_name =&gt; 'Stats'
  
  class Stats &lt; ActiveRecord::Base
      belongs_to :game
  </code></pre>
  
  <p>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.</p>
  
  <pre><code>Stats Load (0.3ms)  SELECT "stats".* FROM "stats" WHERE "stats"."game_id" = 1 LIMIT 1
  </code></pre>
  
  <p>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?</p>
  
  <p><strong>EDIT: Figured it out.</strong></p>
  
  <p>I changed the Game Model to the following:</p>
  
  <pre><code>has_one :home_team_stats, :class_name =&gt; 'Stats', :foreign_key =&gt; "id", :primary_key =&gt; "home_team_stats_id"
  has_one :away_team_stats, :class_name =&gt; 'Stats', :foreign_key =&gt; "id", :primary_key =&gt; "away_team_stats_id"
  </code></pre>