2013-08-05 70 views
0

我是設計足球統計應用程序。我堅持存儲遊戲(匹配)結果。 我有團隊對象和遊戲對象。首先讓遊戲模型看起來像如何在MongoDB中存儲足球隊,比賽和比分

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 

不過貌似隊爲了不匹配分數和長相醜陋。 接下來我創建了存儲團隊的模型分數和它的分數,而遊戲模型有很多分數,但這比以前更難看。

+0

「但它不允許我找到所有的團隊比賽」---爲什麼不呢? –

回答

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 
+0

我需要HABTM'course one teem有很多遊戲(多對多關係)。第二個問題是我需要在一場比賽中得分(我的錯誤,得分意味着進球數)。據我所知,MongoId無法讓模型屬於嵌入式的 – atomAltera

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 

編輯:還有另外的事情要考慮,比如總冠軍,日程表...只是試着想象的事情是如何發生的在現實生活中。你的代碼只是現實的抽象。

希望它有幫助!

+0

我不想指定每個目標的細節,只是每個團隊的目標數量 – atomAltera

+0

我認爲,查詢特定團隊的所有遊戲都有點難看。 – atomAltera

+0

爲什麼只是一個沒有特殊性的常規查詢......'''inhouse_games + games_as_a_vistor''' –