2010-08-24 56 views
1

我有具有以下特點belongs_to的HAS_ONE結構

There are Clubs 
Each Club has Teams 
Each Team has Players 

我有一個用戶表的應用程序。用戶表基本上包含俱樂部經理,球隊經理和玩家登錄系統的用戶名和密碼。

我應該如何構建的模型和表?

我打算創建俱樂部,球隊和球員表。但我不確定展示如何構建它們與用戶表之間的關係。

我可以在每個模型中創建user_id,但關係應該是Club belongs_to User,這看起來不正確。此外,我會結束與用戶模型,具有以下內容

has_one :club 
has_one :team 
has_one :player 

這是不對的。用戶在任何給定時間將只有其中一個。

是否有更好的方法來組織呢?

+0

目前還不清楚用戶代表什麼。如果俱樂部有球隊,而球隊有球員,那麼用戶是什麼?它有什麼,它有什麼? – Chowlett 2010-08-24 12:26:39

+0

對不起。我編輯了這個問題來澄清用戶表。 – Addy 2010-08-24 12:38:30

+0

啊,我明白了。用戶本質上是俱樂部,團隊或玩家之一的「經理」。你有能力改變數據庫中的用戶表嗎? – Chowlett 2010-08-24 12:58:33

回答

1

下軌,has_one真是「至多有一個」。在User中擁有全部三個has_one修飾器是完全有效的。如果你想確保他們只有剛好一個,你可以添加一個驗證,例如:

class User < ActiveRecord::Base 
    has_one :club 
    has_one :team 
    has_one :player 

    validate :has_only_one 

    private 

    def has_only_one 
    if [club, team, player].compact.length != 1 
     errors.add_to_base("Must have precisely one of club, team or player") 
    end 
    end 
end 

因爲你必須改變在數據庫中的用戶表的能力,我想我會把club_idteam_idplayer_idusers,並有以下幾點:

class Club < ActiveRecord::Base 
    has_one :user 
    has_many :teams 
    has_many :players, :through => :teams 
end 

class Team < ActiveRecord::Base 
    has_one :user 
    belongs_to :club 
    has_many :players 
end 

class Player < ActiveRecord::Base 
    has_one :user 
    belongs_to :team 
    has_one :club, :through => :team 
end 

class User < ActiveRecord::Base 
    belongs_to :club 
    belongs_to :team 
    belongs_to :player 

    validate :belongs_to_only_one 

    def belongs_to_only_one 
    if [club, team, player].compact.length != 1 
     errors.add_to_base("Must belong to precisely one of club, team or player") 
    end 
    end 
end 

我甚至被引誘在ClubTeamPlayer月更名爲UserManager,或有has_one :manager, :class_name => "User" dels,但你的電話。

+0

我想過在用戶表中添加三個ID。我們將如何確定已登錄的「實體」。對於每個用戶,只會有一個club_id或team_id或player_id。我將檢查全部三項,以查看用戶是否屬於俱樂部,球隊或球員。 從「用戶」模型到Club/Team/Player的更好方法? – Addy 2010-08-24 13:57:59

+0

我懷疑你可以用'abstract_class?'或多態關聯來做一些聰明的事情;但我傾向於在像'def managed'這樣的用戶中使用方法。俱樂部||團隊||球員end' – Chowlett 2010-08-24 15:01:38

相關問題