Search code examples
ruby-on-railsruby-on-rails-3mongoidself-reference

How do I implement a 'social' aspect with mongoid


I am attempting to create a friend network on a site I am making. I am using Mongoid. How do I instantiate friends?

I assume that Users needs to have a relational association with multiple other users. But the following code:

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

tells me that I have an invalid query. What am I doing wrong? Does anybody have any suggestions on how to get what I am looking for?


Solution

  • Apparently, after much research, Mongoid is not currently capable of cyclical assocations, although it is marked as needed fixing and may be fixed in a future version. The current workaround I am using is as follows:

    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