如何在MongoDB中存储足球队,比赛和得分

时间:2013-08-05 17:11:29

标签: ruby-on-rails ruby mongodb database-design mongoid

我正在设计足球统计应用程序。我坚持存储游戏(比赛)结果。 我有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

但看起来团队订单不匹配得分,看起来很难看。 接下来,我创建了用于存储团队的模型分数和分数,并且游戏模型有很多分数,但这比之前的分数更难看。

2 个答案:

答案 0 :(得分: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
编辑:还有另外需要考虑的事情,比如锦标赛,时间表......试着想象一下现实生活中的事情是怎样的。你的代码只是现实的抽象。

希望它有所帮助!

答案 1 :(得分:0)

我认为自然而然的事情就是认为一个游戏有2个团队(或更多,idk这是什么类型的游戏),并且有一个分数(没有游戏就不存在)。不过,您需要知道哪个分数与哪个团队相关,因此您之间存在关系,因此,您的设计将如下所示:

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