mcnollster
mcnollster

Reputation: 537

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.

Upvotes: 0

Views: 998

Answers (2)

kubum
kubum

Reputation: 469

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

Upvotes: 3

zeroed
zeroed

Reputation: 548

Maybe you can find this a little bit useful:

Migration for games:

class CreateGames < ActiveRecord::Migration
  def change
    create_table :games do |t|
      t.date :match_date

      t.timestamps
    end
  end
end

Migration for teams:

class CreateTeams < ActiveRecord::Migration
  def change
    create_table :teams do |t|
      t.string :name

      t.timestamps
    end
  end
end

Model Game:

class Game < ActiveRecord::Base
  belongs_to :home_team, :class_name => "Team"
  belongs_to :away_team, :class_name => "Team"

  # helper for teams
  def teams
    [home_team, away_team]
  end
end

Add references

class AddReferences < ActiveRecord::Migration
  def change
    change_table :games do |t|
      t.integer :home_team_id
      t.integer :away_team_id
    end
  end
end

In console:

Team.new(name: 'foo').save

Team.new(name: 'bar').save

Game.new(home_team: Team.first, away_team: Team.last).save

Game.first
# => #<Game id: 1, match_date: nil, created_at: "2013-11-20 21:53:41", updated_at: "2013-11-20 21:53:41", home_team_id: 1, away_team_id: 6>

Game.first.teams
# => [#<Team id: 1, name: "foo", created_at: "2013-11-20 21:40:19", updated_at: "2013-11-20 21:40:19">, #<Team id: 2, name: "bar", created_at: "2013-11-20 21:53:12", updated_at: "2013-11-20 21:53:12">]

Upvotes: 1

Related Questions