2010-09-10 14 views
3

我正在嘗試在我製作的網站上創建好友網絡。我正在使用Mongoid。我如何實例化朋友?如何使用mongoid實現'社交'方面

我假設用戶需要與多個其他用戶建立關係關聯。但下面的代碼:

class User 
    include Mongoid::Document 
    references_many :users, :stored_as=>:array, :inverse_of=> :users 
end 

告訴我,我有一個無效的查詢。我究竟做錯了什麼?有沒有人有任何建議如何得到我在找什麼?

回答

3

顯然,經過大量研究,Mongoid目前不具備週期性關聯的能力,雖然它被標記爲需要修復,並且可能會在未來的版本中修復。目前我正在使用的解決方法如下:

class User 
    include Mongoid::Document 
    field :friends, :type => Array, :default => [] 

    def make_friends(friend) 
    self.add_friend(friend) 
    friend.add_friend(self) 
    end 

    def friends 
    ids = read_attribute :friends 
    ids.map { |id| User.find(id)} 
    end 

    def is_friends_with? other_user 
    ids = read_attribute :friends 
    ids.include? other_user.id 
    end 

protected 

    def add_friend(friend) 
    current = read_attribute :friends 
    current<< friend.id 
    write_attribute :friends,current 
    save 
    end 
end 
+0

你能發佈一個鏈接到問題跟蹤#或你見過的討論嗎?是偶然的http://github.com/mongoid/mongoid/issues/labels/wish#issue/140? – 2010-09-30 03:09:52

+0

是的,我認爲就是這樣 – Ryan 2010-10-02 02:32:43

0

簡短的回答是,你不能。 MongoDB沒有連接表的概念,也沒有一般的連接。 Mongoid多對多的「模擬」是通過在每一邊存儲外鍵數組來完成的。

迴應一條評論:MongoDB是一家文檔商店。因此適合「文件」高度異質的情況。在您將廣告客戶存儲爲廣告系列和廣告的子樹時,您必須以紅寶石代碼收集廣告客戶的廣告。如果您的數據具有非常同類的形式,那麼您可以考慮使用關係數據庫。我們經常使用MySQL來關聯對象,然後將MongoDB文檔添加到對象中,以便它們可以擴展。