How to implement the "social" aspect with a mangoid

I am trying to create a network of friends on the site that I am doing. I am using Mongoid. How to create an instance of friends?

I assume that users should have a relational relationship with several 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 request. What am I doing wrong? Does anyone have any suggestions on how to get what I'm looking for?

+3
source share
2 answers

-, 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
+3

, . MongoDB . "" .

: MongoDB - . , "" . Campains , . , . MySQL , MongoDB , .

0

Source: https://habr.com/ru/post/1764234/


All Articles