views:

116

answers:

1

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?

+1  A: 

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
Ryan
Can you post a link to the issue tracking # or discussions you've seen? Is it http://github.com/mongoid/mongoid/issues/labels/wish#issue/140 by chance?
David James
yeah, I think that was it
Ryan