【问题标题】:How do I implement a 'social' aspect with mongoid如何使用 mongoid 实现“社交”方面
【发布时间】:2010-09-10 21:13:33
【问题描述】:

我正在尝试在我正在制作的网站上创建朋友网络。我正在使用 Mongoid。如何实例化好友?

我假设用户需要与多个其他用户建立关系关联。但是下面的代码:

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

告诉我我的查询无效。我究竟做错了什么?有人对如何获得我想要的东西有任何建议吗?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 mongoid self-reference


    【解决方案1】:

    显然,经过大量研究,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
    

    【讨论】:

    【解决方案2】:

    简短的回答是你不能。 MongoDB 没有连接表的概念,也没有一般的连接。 Mongoid 多对多“模拟”是通过在每一侧存储外键数组来完成的。

    回应评论:MongoDB 是一个文档存储。因此,它适合“文档”高度异构的情况。当您将 Advertisers 存储在 Campains 和 Advertisements 的子树中时,您必须以 ruby​​ 代码收集 Advertisers 的广告。如果您的数据具有非常同质的形式,那么您可以考虑使用关系数据库。我们经常使用 MySQL 来关联对象,然后将 MongoDB 文档添加到对象中,以便它们可扩展。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-16
      • 2023-01-01
      • 2016-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多