2014-10-09 11 views
0

我正在構建一個簡單的益智遊戲來學習Rails 4.我有兩個模型在我的Rails應用程序,用戶和拼圖。我試圖瞭解如何構建這兩個模型,以便我可以跟蹤用戶解決的難題,並能夠找到未解決的難題供他玩。謎題不必以任何順序解決,所以我的應用程序只需要能夠找到用戶尚未解決的任何難題。我怎樣才能找到一個難題,用戶還沒有解決我的Rails 4應用程序

一種顯而易見的方法是在用戶和智力遊戲之間創建多對多關係,並在用戶模型上創建一個存儲他已經解決的智力玩家ID的屬性,然後使用簡單的數據庫查詢來查找智力ID不在該列表中,但感覺效率低下...

#Untested code, apologies for typos/bugs 

class User < ActiveRecord::Base 
    has_and_belongs_to_many :solved_puzzles, class_name: "Puzzle" 

    def unsolved_puzzle 
    solved_puzzle_ids = self.solved_puzzles.map {|p| p.id} 
    unsolved_puzzle = self.puzzles.where("id NOT IN ?", solved_puzzle_ids).first 
    end 
end 

class Puzzle < ActiveRecord::Base 
    has_and_belongs_to_many :solved_by, class_name: "User" 
end 

這種方法有什麼問題嗎?其他想法?

在此先感謝您的智慧!

+0

如果你想避免額外的DB命中,那麼你可以簡單地在拼圖添加一個布爾值列,以確定其是否得到解決或沒有。但我認爲你的方式也很好。 – jollarvia 2014-10-09 03:08:01

回答

0

如果您使用has_and_belongs_to_many,則只能存儲用戶和謎題之間的鏈接。我更喜歡has_many:通過關聯,您可以保存特定用戶的謎題狀態。一個用戶和一個謎題之間的關係現在有一個獨立的類與解決狀態。 (未經測試的代碼)

class User 
    has_many :user_puzzles 
    has_many :puzzles, through: user_puzzles 

    def unsolved_puzzle  
    user_puzzles.where(solved: false).first 
    end 

end 

class UserPuzzle 
    belongs_to :user 
    belongs_to :puzzle 
    #has attribute solved 
end 

class Puzzle 
    has_many :user_puzzles 
    has_many :users, through: user_puzzles 
end 
相關問題