2011-02-26 5 views
1
class CreateMatches < ActiveRecord::Migration 
    def self.up 
    create_table :matches do |t| 
     t.integer :result_home 
     t.integer :result_away 
     t.references :clan, :as => :clan_home 
     t.references :clan, :as => :clan_away 

     t.references :league 

     t.timestamps 
    end 
    end 

    def self.down 
    drop_table :matches 
    end 
end 

나는 코드가 모든 것을 제거한다고 생각하고, result_home을 한 ​​클랜에 참조하고 result_away를 다른 것으로 참조해야한다고 생각합니다. 이렇게하는 가장 좋은 방법은 무엇입니까? 나는 has_and_belongs_to_many를 만들 수는 있지만이 경우에는 좋지 않다고 생각합니다.레일 모델 참조 질문

이 조인 관계처럼 보이는

답변

1

그것을 Match를 호출

class Clan < ActiveRecord::Base 
    has_many :home_matches, :class_name => 'Match', :foreign_key => :clan_home 
    has_many :away_matches, :class_name => 'Match', :foreign_key => :clan_away 
    has_many :opponents_at_home, :through => :home_matches, :source => :clan 
    has_many :opponents_away, :through => :away_matches, :source => :clan 
end 

class Match < ActiveRecord::Base 
    belongs_to :clan_home, :class_name => 'Clan' 
    belongs_to :clan_away, :class_name => 'Clan' 
end 

이건 내 개인적인 경험 넘어 조금 나는 :source에 대한 문서의 해석에 분명 100 % 아니에요 (체크 http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html). 그러나, 나는 이것이 올바른 라인을 따라있을 것이라고 생각한다. YMMV.

댓글 및 개선을 환영합니다!

+0

홈 팀과 원정팀에서 선수가 한 것을 추가하고 싶습니다. – methyl

+0

할 수있는 일이 많습니다. 멤버를'Team' 모델로 캡슐화하고'matches_to : away_team ...'등을'Match'에 추가하거나'has_many : away_team_members ... '등을'Match'에 추가 할 수 있습니다. –