2011-02-26 47 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,但我認爲在這種情況下這不是一個好方法。Rails模型引用問題

回答

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 

這是一個有點出乎我的個人經驗,我不是100%對文檔的解釋明確爲:source(檢查http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html)。不過,我認爲這將沿着正確的路線。 YMMV

歡迎評論和改進!

+0

如果我想添加球員在主隊和客隊中所扮演的角色怎麼辦? – methyl 2011-02-26 12:38:21

+0

你可以做很多事情。你可以在'Team'模型中封裝成員並在'Match'上擁有'belongs_to:away_team ...'等,或者你可以在'Match'上直接添加'has_many:away_team_members ...'等。 – 2011-02-26 13:00:03