0

我正在设计足球统计应用程序。我坚持存储游戏(比赛)结果。我有 Team 对象和 Game 对象。首先我让游戏模型看起来像

class Game
  include Mongoid::Document

  belongs_to :team_1, class_name: "Team"
  belongs_to :team_2, class_name: "Team"  

  field :score_1, type: Integer
  field :score_2, type: Integer

但它不允许我找到所有团队游戏。接下来我决定做这样的事情:

class Game
  include Mongoid::Document

  has_and_belongs_to_many :teams
  field :scores, type: Array

但看起来球队的顺序与分数不匹配,而且看起来很丑。接下来我创建了模型 Score 用于存储团队及其得分,而 Game 模型有很多 Score,但这比以前的更难看。

4

2 回答 2

1

我不知道你想要实现什么样的模型,但在我看来,你的模型应该反映你正在建模的游戏本质的现实。

因此,考虑到这种方法,您的类设计应如下所示:

class Game
  class InvalidScorerError < Exception ; end
  include Mongoid::Document
  belongs_to :home_team, class_name: "Team"
  belongs_to :away_team, class_name: "Team"
  embeds_many :goals

  field :home_team_goals, type: Integer, default: 0
  field :away_team_goals, type: Integer, default: 0

  def register_a_goal(team)
    if team == home_team
        self.home_team_goals += 1
        self.save!
    elsif team == away_team
        self.away_team_goals += 1
        self.save!
    else
        raise InvalidScorerError, "Team should be either home or away!"
    end
  end

  def total_match_goals
    self.home_team_goals + self.away_team_goals
  end
end

class Team
  include Mongoid::Document
  has_many :inhouse_games, class_name: "Game", inverse_of: :home_team
  has_many :games_as_a_visitor, class_name: "Game", inverse_of: :away_team
end

编辑:还有其他事情需要考虑,比如冠军赛、赛程……试着想象现实生活中的事情是如何发生的。您的代码只是对现实的抽象。

希望能帮助到你!

于 2013-08-05T21:40:51.260 回答
0

I think the natural thing is to think that a game has 2 teams (or more, idk what kind of game is this), and has one score (that does not exist without a game). Still, you need to know which score is related with which team, so you have a relationship between them, therefore, your design would look like this:

class Game
  include Mongoid::Document
  has_many :teams #I don't get why you would need HABTM
  embeds_one :score
end

class Team
  include Mongoid::Document
  belongs_to :game
  has_many :scores
end

class Score
  include Mongoid::Document
  embedded_in :game
  belongs_to :team
  field :score, type: Integer
end
于 2013-08-05T17:49:28.833 回答