2

私は、ゲームを追跡するための Ruby Web アプリである DataMapper との単純な関係に取り組んでいます。ゲームは 4 人のプレーヤーに属し、各プレーヤーは多くのゲームを持つことができます。player.games.size を呼び出すと、ゲームが関連付けられていることがわかっているプレイヤーに対して、0 という結果が返されるようです。現在、プレーヤーの関連付けをゲームから引き出すことができますが、player.games が空である理由がわかりません。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
4

3 に答える 3

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
于 2010-03-25T03:07:48.233 に答える
1

次のことを試しましたか。

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

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

現在、関連するバグを探しています。

于 2010-07-07T01:09:12.833 に答える
0

単一テーブル継承を使用して、目的の結果を達成できるはずです。ただし、あるゲームではプレーヤー1であり、別のゲームではプレーヤー2であるプレーヤーをどのように処理するかについて考える必要があるかもしれません。

私のサンプルコードは参考用です。テストされていませんが、動作するはずです。

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
于 2011-01-19T15:16:55.187 に答える