Jonathon Doesen
Jonathon Doesen

Reputation: 563

Has_many: through in Rails. Can I have two foreign keys?

I am a rails newbie and I am trying to create a database schema that looks like the following:

There are many matches. Each match has 2 teams.

A team has many matches.

The team model and match model are joined together through a competition table.

I have that competition model with a match_id and a team1_id and a team2_id.

But I don't know how to make this work or if it's even the best way to go about it. I don't know how to make certain teams team1 and others team2.... two foreign keys? Is that possible?

The match table also needs to hold additional data like team1_points and team2_points, winner and loser, etc.

Upvotes: 1

Views: 1120

Answers (2)

Oriol Gual
Oriol Gual

Reputation: 424

I faced a similar problem, and extending the previous answer, what I did was:

class Game < ActiveRecord::Base

  def self.played_by(team)
    where('team1_id = ? OR team2_id = ?', team.id, team.id)
  end
end

class Team < ActiveRecord::Base

  def games
    @games ||= Game.played_by(self)
  end
end

This way, Team#games returns an ActiveRecord::Relation instead of an Array, so you can keep chaining other scopes.

Upvotes: 1

Marc Talbot
Marc Talbot

Reputation: 2059

You can have as many foreign keys as you want in a table. I wrote an application that involved scheduling teams playing in games.

The way that I handled this in the Game class with the following:

class Game < ActiveRecord::Base
  belongs_to :home_team, :class_name => 'Team', :foreign_key => 'team1_id'
  belongs_to :visitor_team, :class_name => 'Team', :foreign_key => 'team2_id'

You can add appropriate fields for team1_points, team2_points, etc. You'll need to set up your Team model with something like:

class Team < ActiveRecord::Base
  has_many :home_games, :class_name => 'Game', :foreign_key => 'team1_id'
  has_many :visitor_games, :class_name => 'Game', :foreign_key => 'team2_id'

  def games
    home_games + visitor_games
  end

  #important other logic missing
end

Note that some of my naming conventions were the result of having to work with a legacy database.

Upvotes: 2

Related Questions