2014-01-09 83 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阵列,以获得给定的球员的联赛。

相关问题