2009-09-01 2 views
1

시즌을 통해 축구 팀을 추적하는 응용 프로그램을 만들고 있습니다. 하지만 난 데이터베이스의 디자인에 붙어있다. 하나의 경기에는 홈 팀과 원정 팀이 있습니다. home_team과 away_team이라는 두 개의 외래 키가있는 조명기 모델을 만들었지 만, 제대로 작동 할 수있는 연관성은 없습니다. 어떤 아이디어? 각 조명기는 리그에 속합니다.레일의 다단계 연결

답변

7

간단한 대답은 다음과 같습니다

class Fixture < ActiveRecord::Base 
    belongs_to :home_team, :class_name => "Team", :foreign_key => :home_team 
    belongs_to :away_team, :class_name => "Team", :foreign_key => :away_team 
end 

class Team < ActiveRecord::Base 
    has_many :fixtures 
end 

하지만 Team.fixtures이 작동하지 않기 때문에 경우이 좋지 않습니다.

class Team < ActiveRecord::Base 
    has_many :home_fixtures, :class_name => "Fixtures", :foreign_key => :home_team 
    has_many :away_fixtures, :class_name => "Fixtures", :foreign_key => :away_team 
end 

두 개의 모음을 제공하지만 루비에서이 모음집을 사용하면 icky가 발생합니다.

class Team < ActiveRecord::Base 
    def fixtures(*args) 
    home_fixtures.all(*args) + away_fixtures.all(*args) 
    end 
end 

너무 문제가 있습니다. 정렬 및 제한이 모두 처리됩니다. (ㅎ, 말장난, 누가 알았습니까?).

class Team < ActiveRecord::Base 
    has_many :fixtures, :finder_sql => 'SELECT * FROM fixtures where (home_team = #{id} or away_team = #{id})' 
    has_many :home_fixtures, :class_name => "Fixtures", :foreign_key => :home_team 
    has_many :away_fixtures, :class_name => "Fixtures", :foreign_key => :away_team 
end 

이것은보기 싫지만 작동 할 수 있습니다. finder_sql은 필요한 것을 수행하는 것 같습니다. 이 범위이기 때문에 훨씬 읽기 전용 협회처럼 행동한다,

class Fixture < ActiveRecord::Base 
    named_scope :for_team_id, lambda{|team_id| {:conditions => ['(home_team = ? or away_team = ?)', team_id, team_id]} } 
    belongs_to :home_team, :class_name => "Team", :foreign_key => :home_team 
    belongs_to :away_team, :class_name => "Team", :foreign_key => :away_team 
end 

class Team < ActiveRecord::Base 
    def fixtures 
    Fixtures.for_team_id(id) 
    end 
end 

이 마지막 솔루션은 내가 고수하려는 하나이며, :finder_sql 방지 :

다른 옵션은 named_scope를 사용하는 것입니다 (실제로는? 더 많은 조건을 병합하는 방법을 어떻게 알 수 있습니까? 때로는 하위 쿼리, 하위 쿼리를 수행합니까? 그럴 필요가 없습니다.).

희망이 도움이됩니다.

0

Team 모델과 Something 모델이 있다고 가정하면 후자는 home_team_idaway_team_id입니다.

class Something < ActiveRecord::Base 
    belongs_to :home_team, :class_name => 'Team' 
    belongs_to :away_team, :class_name => 'Team' 

당신은 something.away_teamsomething.home_team로 참조됩니다.