2013-01-20 134 views
0

我有點沉迷於如何與我有一些模型。希望得到一些提示或想法!Rails 3模型關係

比方說,我有3個模型,名爲「MinorTeam」,「MajorTeam」和「遊戲」。每場比賽都參考兩支球隊;但我如何指定它可以是主隊還是小隊呢?

has_one :team_1, :class_name => "MajorTeam" 
# or 
has_one :team_1, :class_name => "MinorTeam" 

兩個團隊模型基本一樣,所以我不能簡單地添加一個主要/次要標誌的團隊模式。有任何想法嗎?

回答

0

多態協會應該工作。你可能需要稍微調整一下才能正確使用,但通過使用它們,除了玩遊戲之外,團隊類並不一定都是。

module Team 
    extend ActiveSupport::Concern 
    included do 
    has_many :home_games, :class_name => "Game", :as => :team_1 
    has_many :away_games, :class_name => "Game", :as => :team_2 
    end 
end 

class MajorTeam < ActiveRecord::Base 
    include Team 
end 

class MinorTeam < ActiveRecord::Base 
    include Team 
end 

class Game < ActiveRecord::Base 
    belongs_to :team_1, :polymorphic => true 
    belongs_to :team_2, :polymorphic => true 
end 

我假設你的意思是你has_onebelongs_to,爲has_one意味着每個隊只屬於一個遊戲,這似乎像它可能是不正確的。如果我錯了,讓我知道。

+0

糟糕,這是一個糟糕的錯字哈哈。是的,謝謝! – user1769426