我正在与DataMapper建立一个简单的关系,这是一个用于跟踪游戏的ruby webapp。一个游戏属于4个玩家,每个玩家可以有很多游戏。 当我打电话给player.games.size时,我似乎回到0的结果,对于我知道有与之相关的游戏的玩家。我目前能够将玩家协会拉出游戏,但无法弄清楚为什么玩家游戏是空的。 我是否需要在has n关联上定义parent_key,或者还有其他我缺少的东西?
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
答案 0 :(得分: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 :(得分:1)
您是否尝试过以下操作:
class Game
has n, :Players, :through => Resource
end
class Player
has n, :Games, :through => Resource
end
我正在寻找相关的bug。
答案 2 :(得分:0)
您应该能够使用单表继承来实现所需的结果。虽然你可能需要考虑如何处理玩家在一个游戏中的玩家和在另一个游戏中玩玩家二的玩家。
我的示例代码仅供参考。它尚未经过测试但应该有效。
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