2017-03-05 63 views
2

我是Rails的一名初學者,但隨時都在學習。我正在嘗試創建一個錦標賽入場門戶網站,一個球隊可以進入參加錦標賽的選手。我已經完成了關於關聯的一些閱讀,但是在這種情況下如何應用它們會遇到一些麻煩。比賽 - >球隊 - >球員協會

作爲基本概述:

  • 一個比賽,有很多球隊。
  • 每隊有很多球員
  • 因此一個巡迴賽也有不少玩家(通過團隊
    進入)

這裏是我這個代碼,但我不知道這是正確的,因爲我無法獲得與玩家相關的任何tournament_ids。

(tournament.rb)

class Tournament < ApplicationRecord 
    has_many :teams 
    has_many :players, :through => :teams 
end 

(team.rb)

class Team < ApplicationRecord 
    belongs_to :tournament 
    has_many :players 
end 

(player.rb)

class Player < ApplicationRecord 
    has_one :team 
    has_one :tournament, :through => :team 
end 

內玩家桌子上有兩個TEAM_ID & tournament_id字段,但是我只能通過關聯來填充team_id字段,當我嘗試使用CONSOL時即

我想知道是否有什麼與我的協會不協調。

回答

0

'belongs_to','has_many','has_one'的用法當然取決於數據庫中的數據模型。

如果您在players表TEAM_ID外鍵,那麼您需要定義播放器類爲:

class Player < ApplicationRecord 
    belongs_to :team 
    has_one :tournament, :through => :team 
end 

此外,我真的相信那場比賽< - >團隊應該有很多-to-many關聯(如果球隊可以參加許多比賽當然)。我建議增加模型TeamTournament並確定最終的模型結構爲:

class Tournament < ApplicationRecord 
    has_many :team_tournaments 
    has_many :teams, :through => :team_tournaments 
    has_many :players, :through => :teams 
end 

class TeamTournament < ApplicationRecord 
    belongs_to :team 
    belongs_to :tournament 
end 

class Team < ApplicationRecord 
    has_many :team_tournaments 
    has_many :tournaments, :through => :team_tournaments 
    has_many :players 
end 
+0

出於興趣如何使用TeamTournament模型?我在這個地方的幾個不同的答案和例子中看到了一個類似的概念,但我無法讓我的頭腦圍繞使用/概念 - 可能缺乏經驗。 – afishintaiwan

0

Player類應該有belongs_to的與Team和比賽

class Player < ApplicationRecord 
    belongs_to :team 
    belongs_to :tournament 
end 
+0

'belongs_to:tournament,:through =>:team'''將不起作用 –

+0

'belongs_to'在當前表上使用foreign_key。除非'參賽選手'表格包含對錦標賽的參考,否則錦標賽可以定義爲'''has_one:錦標賽,通過:: team''' –

0

OK協會。我假設你的問題是關於你的模型協會,而不是如何建立關聯從player得到tournament_id等等。所以我會盡力向您提供一些關於您的項目的建議,並且可以爲其設置關聯。

因爲我得到了你的門戶網站的想法...你想tournament有很多teamsteam有很多players。但是你想從player得到tournament_id。我相信你不想這樣做,因爲在現實生活中,錦標賽確實可能「擁有」一些球員,但每個球員都不必參加某個錦標賽。他可以參加很多比賽。所以你不需要爲此設置關聯。錦標賽和球隊也是如此。但是由於球隊擁有球員,他必須屬於該球隊。所以你需要關聯。

結束語我的設置你的將是這樣的:

(tournament.rb)

class Tournament < ActiveRecord::Base 
    has_many :teams 
end 

(team.rb)

class Team < ActiveRecord::Base 
    has_many :players 
end 

(player.rb)

class Player < ActiveRecord::Base 
    belongs_to :team 
end 

還有一個關於如何你可以得到tournament其中某些team參加無直接關聯:

team = Team.first # just take some team 
Tournament.includes(:teams).where(teams: { id: team.id }) 

用同樣的方法,你可以實現你的其他目標(拿到賽某些球員屬於等等)。但是這種情況不需要關聯。當對象與另一個概念相關時,需要關聯。