2014-01-09 2 views
1

post에 설명 된대로 belongs_to :x, through: :y 관계는 대리인 메서드를 사용하는 것이 가장 좋습니다.레일즈에 belongs_to through 메소드가없는 이유는 무엇입니까?

레일즈가 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

이렇게하면됩니다.

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 

그런 다음 해당 선수의 리그를 얻기 위해 주어진 리그에서 선수 또는 player.league의 배열을 얻을 수 league.players를 호출 할 수 있습니다 .

관련 문제