0

I have a project with 2 models, Game and Team. A Game has two Teams, an away team and a home team. There is a set number of Teams(no more get created) and each will belong to many Games.

I want to be able to do @game.home_team.name instead of @game.teams.find_by_id(@game.home_team_id).first.name. I'm not sure if I can do that without creating two additional models, AwayTeam and HomeTeam, which will have the same columns as Team except for an additional :game_id and maybe :type.

Currently the HABTM relationship between Games and Teams works but I have no way of turning a Team into a HomeTeam or AwayTeam once it belongs to a Game.

game.rb

class Game < ActiveRecord::Base
  has_and_belongs_to_many :teams
  has_one :away_team, -> {where(type:'away')}, class_name: 'Team' 
  has_one :home_team, -> {where(type:'home')}, class_name: 'Team'
end

team.rb

class Team < ActiveRecord::Base

  has_and_belongs_to_many :games
  # has_many :away_teams
  # has_many :home_teams
end

###

# class AwayTeam < Team
#   belongs_to :game
#   belongs_to :team
# end
# class HomeTeam < Team
#   belongs_to :game
#   belongs_to :team
# end

games_controller.rb

def create
  @game = Game.create(game_params)
  @game.teams << Team.find_all_by_id([ @game.away_team_id, @game.home_team_id ])
  @game.away_team = @game.teams.find_by_id(@game.away_team_id)
  @game.home_team = @game.teams.find_by_id(@game.home_team_id)
  @game.save
end

Any help would be really appreciated, thanks.

1 Answers1

1

Try to add one additional model GameTeam and make has_many :through relation

  class GameTeam
    belongs_to :game
    belongs_to :team
    validates :team_type, presence: true
  end

  class Game
    has_many :game_teams
    has_may :teams, through: :game_teams
  end

Then you can make game.teams to fetch all teams. You can additionally implement scopes of methods to get home or away team by GameTeam type

Stanislav Mekhonoshin
  • 4,276
  • 2
  • 20
  • 25