1

I have two models Game and Team:

    class Game < ActiveRecord::Base
      belongs_to :home_team, class_name: 'Team', required: true
      belongs_to :visitor_team, class_name: 'Team', required: true
    end

and

    class Team < ActiveRecord::Base
      has_many :games
    end

The relationship has_many :games doesn't work (I would have to specify class_name but in this case I have two class names). I have to differentiate home and visitor.

Any idea on how to design this?

Thanks

2 Answers2

0

You have to specify the foreign_key, assuming you have columns home_team_id and visitor_team_id in games table:

has_many :home_games, class_name: 'Game', foreign_key: :home_team_id
has_many :visitor_games, class_name: 'Game', foreign_key: :visitor_team_id
Yang
  • 1,915
  • 1
  • 9
  • 15
  • This is wrong. It has nothing to do with the declaration of `belongs_to`. – user229044 Dec 21 '15 at 18:24
  • Hi, thanks for your response. However the foreign_key doesn't change anything here. I'm still getting "SQLException: no such column: games.team_id". I think the issue is probably in the declaration of has_many but I don't know what's missing. –  Dec 21 '15 at 18:25
  • Sorry, copied the wrong lines to edit... I have updated my answer. – Yang Dec 21 '15 at 18:30
0

has_many will look for a foreign key with the same name as the class you're working in.

In this case, Rails will assume there is a team_id in the associated Game class, linking back to the Team.This isn't the case, so you need to be more explicit.

In this case, you also don't have a single link from a Game back to a Team. There are two different links between Game and Team, so you need to represent both of these links as associations:

class Team < ActiveRecord::Base
  has_many :home_games, class_name: 'Game', foreign_key: :home_team_id
  has_many :visitor_games, class_name: 'Game', foreign_key: :visitor_team_id
end

If you want to get all games for a given team, regardless of whether they are home or visitng games, you can define a method:

class Team < ActiveRecord::Base
  has_many :home_games, class_name: 'Game', foreign_key: :home_team_id
  has_many :visitor_games, class_name: 'Game', foreign_key: :visitor_team_id

  def games
    Game.where('home_team_id = ? or visitor_team_id = ?', id, id)
  end
end
user229044
  • 232,980
  • 40
  • 330
  • 338
  • Thanks! :) That's exactly what I currently have but I was hoping to replace my "games" method by a pretty has_many. –  Dec 21 '15 at 18:31