5
實現一個與activerecord有兩個關聯的最佳方式是什麼?ActiveRecord有兩個關聯
我有團隊和遊戲模型。每個團隊將有多種遊戲@team.games
。一場比賽將有兩支球隊@game.hosting_team
和@game.opposing_team
。
我開始與兩個belongs_to/has_one
協會,但然後@team.games
只會返回他們的主場比賽。
我能想到的另一個選擇是使用HABTM並使用驗證器來確保只有記錄。唯一缺少的是跟蹤主隊。似乎我需要一個有很多通過關聯,但我不完全確定...
感謝您的幫助。
這是兩個has_many關聯的外觀示例。這裏的問題是我得打個電話team.games
和team.opponents
得到他們的比賽
class Team < ActiveRecord::Base
has_many :games
has_many :opponents, :class_name => "Team"#, :foreign_key => ""
end
class Game < ActiveRecord::Base
belongs_to :team, :class_name => "Team" #, :foreign_key => "team_id"
belongs_to :opponent, :class_name => "Team" #, :foreign_key => "opponent_id"
end
的完整列表,我想這樣的事情,但是這顯然並不怎麼belongs_to的作品。
class Team < ActiveRecord::Base
has_many :games
end
class Game < ActiveRecord::Base
belongs_to :hosting_team
belongs_to :opposing_team
end
我希望的api看起來像這樣。
@team.games # return all games home or away
@game.hosting_team # Team
@game.opposing_team # Team
你能calrify模型的關係,也許發佈你的db/schema.rb? – 2010-11-28 19:48:44
謝謝。我編輯了這個問題。 – jspooner 2010-11-28 20:13:36