2014-01-09 80 views
1

post所述,belongs_to :x, through: :y關係最好通過委託方法實現。爲什麼Rails沒有belongs_to through方法?

是否有一個特別的原因(技術原因,設計選擇)爲什麼Rails不支持belongs_to關係?

class Division 
    belongs_to :league 
    has_many :teams 
end 

class Team 
    belongs_to :division 
    has_many :players 
end 

class Player 
    belongs_to :team 
    belongs_to :division, through: :team # WON'T WORK 
end 

回答

5

它會這樣工作而不是使用through。

belongs_to :division, class_name: Team 
1

我不明白爲什麼,但ActiveRecord方法中有一致的自上而下模式。您正在尋找已經被has_many :through提供的 - 它只是一個將本聲明的祖先,而不是派生對象的物質的功能:

的的has_many:通過協會還設立 「有用的快捷鍵「通過嵌套的has_many關聯。例如,如果一個文檔有很多部分,而一個部分有很多段落,你有時可能想要獲得文檔中所有段落的簡單集合。 [source: Rails Guides]

在你的情況,這將如下所示:

class Division 
    belongs_to :league 
    has_many :teams 
    has_many :players, through: :teams 
end 

class Team 
    belongs_to :division 
    has_many :players 
end 

class Player 
    belongs_to :team 
end 

然後可以調用league.players讓玩家在給定的聯賽還是player.league陣列,以獲得給定的球員的聯賽。

相關問題