2010-06-24 79 views
1

我有三個需要關聯的類,我不知道該怎麼做。關聯兩個已經關聯的資源

User類當然是一個用戶,Game代表一個遊戲,GameTurn代表遊戲中的一個轉向。遊戲屬於用戶,發起遊戲的用戶和GameTurn屬於用戶,即玩過該玩家的用戶。

我想要做的就是通過GameTurn關聯用戶和遊戲,以便我可以快速獲取遊戲中的玩家列表以及玩家玩過的遊戲列表。我只是不知道該怎麼做這個,並且不想搞亂任何東西,因爲遊戲已經屬於用戶。 (儘可能刪除與屬性無關的屬性,以使定義更具可讀性)。

下面是相關類的定義

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 

我與一般的ORM相當缺乏經驗,所以如果這些協會可以更好地做另一種方式,請讓我知道。

感謝

回答

2

我從來沒有用過datamapper,但我相信你需要的是像

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 
+0

誰能確認這是否是我想要的嗎?我想可能有問題,因爲遊戲已經屬於一個用戶(用不同的方式,而不是我想要這種關係) – 2010-06-24 02:25:06

+0

哦等等!我沒有那樣做。對不起,我認爲每個遊戲屬於一個用戶,一個開始它的用戶,但我剛剛意識到我沒有這樣做,因爲我不在乎誰開始遊戲(如果我需要知道,這是第一個人玩),所以沒有歧義,這確實有效。謝謝! – 2010-06-24 02:30:10

+0

我很高興能幫到你:] – 2010-06-24 11:31:11