views:

155

answers:

2

I am working on a simple relationship with DataMapper, a ruby webapp to track games. A game belongs_to 4 players, and each player can have many games. When I call player.games.size, I seem to be getting back a result of 0, for players that I know have games associated with them. I am currently able to pull the player associations off of game, but can't figure out why player.games is empty. Do I need to define a parent_key on the has n association, or is there something else I'm missing?

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  A: 

Still haven't figured out a way that feels right, but for now I am using the following workaround. Anyone know of a better way to accomplish this?

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
jing
A: 

Have you tried the following:

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

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

I'm looking for a related bug now.

Mark Essel
I think :through => Resource will create an association table and an array on the objects. I was hoping I could keep individual fields, but I guess you could always create accessors or change the object models a bit.
jing