views:

18

answers:

1

I have three classes that need to be related, and I'm not sure how to do it.

The User class, is of course for a user, Game represents a game, GameTurn represents a turn in the game. Game belongs to a user, the user who initiated the game, and GameTurn belongs to a user, the user who played that turn.

What I want to do is associate User and Game through GameTurn, so I can quickly get a list of players in a Game, and a list of Games that a player played in. I'm just not sure how to do this, and don't want to mess anything up since Game already belongs to a user. (properties not related were removed where possible, to make the definitions more readable).

Here are the relevant class definitions

class User
    include DataMapper::Resource

    property :id, Serial
    property :name, String
    property :created_at, DateTime
    property :password, BCryptHash

    has n, :gameTurns
end

class Game
    include DataMapper::Resource
    property :id, Serial
    property :created_at, DateTime
    property :finished, Boolean, :default=>false
    property :finished_at, DateTime
    property :length, Boolean #Number of turns

    has n, :gameTurns
end

class GameTurn
    include DataMapper::Resource
    property :id, Serial
    property :isText, Boolean
    property :text, String
    property :image, Text

    belongs_to :game
    belongs_to :user
end

I'm pretty inexperienced with ORMs in general, so if any of these associations can be better done another way, please let me know.

Thanks

+2  A: 

I've never used datamapper, but I believe what you need is something like

class User 
   # ...
   has n, :gameTurns
   has n, :games, :through => :gameTurns
end 

class Game 
   # ...
   has n, :gameTurns
   has n, :users, :through => :gameTurns
end 

class GameTurn
   # ...
   belongs_to :game 
   belongs_to :user 
end
j.
Can anyone confirm if this is what I want? I imagine there might be problems since Game already belongs to a user (in a different way than I want this relationship to be)
Jeffrey Aylesworth
oh wait! I didn't do that. Sorry, I thought that each Game belonged to a User, the one who started it, but I just realized I didn't do that because I don't care who started the game (and if I need to know, it's the first person to play), so there is no ambiguity, and this does work. Thanks!
Jeffrey Aylesworth
I'm glad I could help :]
j.