2011-12-29 15 views
0

私はモデル国(「チーム」と同じです)とモデルマッチを持っています。私は両方の家庭で一致記録を持つシナリオを構築しようとしています&離れたチーム。同じモデルの2つの関連付けが可能ですか?

モデル

class Country < ActiveRecord::Base 
    has_many :home_matches, :foreign_key => 'home', :class_name => "Match" 
    has_many :away_matches, :foreign_key => 'away', :class_name => "Match" 
end 

class Match < ActiveRecord::Base 
    belongs_to :home, :class_name => "Country", :foreign_key => "home" 
    belongs_to :away, :class_name => "Country", :foreign_key => "away" 
end 

スキーマ

create_table "countries", :force => true do |t| 
    t.string "name" 
    t.text  "bio" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    end 

    create_table "matches", :force => true do |t| 
    t.datetime "matchdate" 
    t.integer "home" 
    t.integer "away" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    end 

問題

私はちょうどしたい場合、これがうまく機能:

> canada.away_matches 
> japan.home_matches 

しかし、どの国で試合が行われているのですか?

更新:

私は別の回答で答えを見つけました。 ActiveRecord has two association

私は次のコードで、私の国のモデルを更新しました:

def matches 
    Match.where("home = ? OR away = ?", self, self) 
end 

今、私が照会できます。

> canada.home_matches 
> canada.away_matches 
> canada.matches 

をし、所望の結果を得ます。

答えて

関連する問題