2012-12-20 108 views
0

我在嘗試一些非常簡單的事情。此時我有三種模式:模型關係多對多關係實體上的屬性

Player >> PlayerMatch >> Match 

class Match < ActiveRecord::Base 
    attr_accessible :date, :goals_team_a, :goals_team_b 
    has_many :PlayerMatches 
    has_many :Players, :through => :PlayerMatches 
end 

class Player < ActiveRecord::Base 
    attr_accessible :name, :password_confirmation, :password, :user 
    has_many :PlayerMatches 
    has_many :matches, :through => :PlayerMatches 
end 

class PlayerMatch < ActiveRecord::Base 
    attr_accessible :match_id, :player_id, :team 
    belongs_to :player 
    belongs_to :match 
end 

模型PlayerMatch是連接實體。在每位球員參加比賽時,他可以在A隊或B隊,這就是爲什麼我在PlayerMatch上製作該屬性隊的原因。

如何設置這個值隊每場比賽?我想要做的事,如:

p = Player.new 
//set players attributes 
m = Match.new 
//set match attributes 

p.matches << m 

現在我只想把他的團隊對特定的匹配。

在此先感謝!

回答

0

使用你已經建立了模型,你可以做這樣的事情:

p = Player.create 
m = Match.create 
pm = PlayerMatch.create(:player => p, :match => m, :team => 'Team') 

如果你想在你的榜樣自動創建PlayerMatch,你可以事後檢索,並設置團隊在這一點上:

p = Player.create 
m = Match.create 
p.matches << m 

pm = p.matches.where(:match_id => m.id).first 
pm.update_attributes(:team => 'Team') 

除非你說的個別球員可以爲不同的團隊,雖然打不同的比賽,好像你可能希望玩家belong_to一個團隊來代替。

This post也有與此相關的問題的一些信息。

+0

謝謝你,漂亮的迴應...我會更多地考慮了模型,並嘗試不同的方法來做到這一點 –

+0

@Gabriel索薩請接受的答案是否能解決您的問題或回答了這個問題。 – cbascom