Вопрос

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
Это было полезно?

Решение

You didn't say much about the problem. But I think you are working too hard. If a team can play several games and a game includes more than one team, then you you need a many to many relation. This requires a third table, and best practice is a has_many :through relation. It will look something like:

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

Now you have the winner and loser attributes, but you don't need to roll your own method to count games for a team. Just say team.games.count and similarly game.teams is the teams assigned to the game.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top