Search code examples
ruby-on-railsforeign-keysruby-on-rails-4model-associations

Rails - associate two different fields from one model as one association


I have two fields on my Game model, home_team_id and away_team_id.

I would like to associate these two fields as the teams tied to the Game.

These teams can belong to more than one game so I have on my Team model

has_many :games

I'm not sure what to put on my Game model.

has_many :teams

doesn't work because it doesn't know to look for home_team_id and away_team_id. Is there a way to tell it that there are two different keys for teams?

I've also tried this but it doesn't work either.

has_one :away_team, :class_name => 'Team', :foreign_key => 'id'
has_one :home_team, :class_name => 'Team', :foreign_key => 'id'

In the end I just want to be able to run @game.teams in the console and get the home and away teams returned.


Solution

  • Assuming that you have created your Game migration like:

    class CreateGames < ActiveRecord::Migration
      def change
        create_table :games do |t|
          t.integer :home_team_id
          t.integer :away_team_id
    
          t.timestamps
        end
      end
    end
    

    You can archive it by specifying your model like:

    class Game < ActiveRecord::Base
      belongs_to :away_team, class_name: 'Team', foreign_key: 'away_team_id'
      belongs_to :home_team, class_name: 'Team', foreign_key: 'home_team_id'
    
      def teams
        [away_team, home_team]
      end
    end