2010-03-23 94 views
2

我正在與DataMapper(一個用於跟蹤遊戲的ruby webapp)的簡單關係。遊戲屬於4個玩家,每個玩家可以有很多遊戲。 當我打電話給player.games.size時,我似乎得到了0的結果,對於我認識的玩家來說有與他們相關的遊戲。我目前能夠將玩家關聯關閉,但不知道爲什麼player.games是空的。 我是否需要在has n關聯中定義parent_key,還是還有其他我缺少的東西?Datamapper與多個鍵具有n關係

class Game 
    belongs_to :t1_p1, :class_name => 'Player', :child_key => [:player1_id] 
    belongs_to :t1_p2, :class_name => 'Player', :child_key => [:player2_id] 
    belongs_to :t2_p1, :class_name => 'Player', :child_key => [:player3_id] 
    belongs_to :t2_p2, :class_name => 'Player', :child_key => [:player4_id] 
    ... 
end 

class Player 
    has n, :games 
    ... 
end 

回答

1

仍然沒有想通了,感覺不錯的方式,但現在我使用以下解決方法。任何人都知道有更好的方法來實現這一目標?

class Player 
    has n, :games # accessor doesn't really function... 
    def games_played 
    Game.all(:conditions => ["player1_id=? or player2_id=? or player3_id=? or player4_id=?", id, id, id, id]) 
    end 
end 
1

你有沒有試過如下:

class Game 
    has n, :Players, :through => Resource 
end 

class Player 
    has n, :Games, :through => Resource 
end 

我正在尋找一個相關的錯誤了。

+0

我認爲:through =>資源會在對象上創建關聯表和數組。我希望能保留單個字段,但我想你總是可以創建訪問器或改變對象模型。 – jing 2010-07-13 14:33:20

0

您應該可以使用Single Table Inheritance來獲得所需的結果。雖然您可能需要考慮如何處理玩家在一場比賽中是玩家一,玩家二在另一場比賽中。

我的示例代碼僅供參考。它沒有經過測試,但應該工作。

class Player 
    property :id,    Serial 
    property :name,   String 
    property :player_number, Discriminator 
end 

class PlayerOne < Player 
    has n, :games, :child_key => [ :player1_id ] 
end 

class PlayerTwo < Player 
    has n, :games, :child_key => [ :player2_id ] 
end 

class PlayerThree < Player 
    has n, :games, :child_key => [ :player3_id ] 
end 

class PlayerFour < Player 
    has n, :games, :child_key => [ :player4_id ] 
end 

class Game 
    belongs_to :player1, :class_name => 'PlayerOne', :child_key => [:player1_id] 
    belongs_to :player2, :class_name => 'PlayerTwo', :child_key => [:player2_id] 
    belongs_to :player1, :class_name => 'PlayerThree', :child_key => [:player3_id] 
    belongs_to :player2, :class_name => 'PlayerFour', :child_key => [:player4_id] 
end