1

I'm trying to find the best way to model a game in relation to teams.

The end goal is to be able to call things like:

@game.winner
@game.loser
@team.games

The first two relations are working, but the games one is not. Using has_many (see below), I get ERROR: column games.team_id does not exist which I would normally work around by using whatever the equivalent to :foreign_key => winner_id, but how can I have it checkout both winner_id and loser_id?

Is the only option to create a method in the teams model like so:

def games
  won = Game.where(:winner => id)
  lost = Game.where(:loser => id)
  won + lost
end

So far what I'm doing is:

class Game < ActiveRecord::Base
  has_one :winner, class_name: "Team"
  has_one :loser,  class_name: "Team"
end


class Team
  has_many :games
  # or something that actually works
end
4

1 回答 1

2

你对这个问题没有多说。但我觉得你工作太努力了。如果一个团队可以进行多场比赛,而一场比赛包括多个团队,那么您需要多对多关系。这需要第三个表,最佳实践是has_many :through关系。它看起来像:

class Game < ActiveRecord::Base
  has_many :teams, through: assignment
  has_one :winner, class_name: 'Team', through: :assignment, order: 'score DESC'
  has_one :loser,  class_name: 'Team', through: :assignment, order: 'score ASC'
end

class Team
  has_many :games, through: :assignment
end

class Assignment < ActiveRecord::Base
  belongs_to :game
  belongs_to :team
end

现在您有了赢家和输家的属性,但您不需要滚动自己的方法来计算团队的比赛数。只是说team.games.count ,同样game.teams是分配给游戏的团队。

于 2013-11-03T01:45:08.163 回答