2010-09-10 16 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文档添加到对象中,以便它们可以扩展。