The user has many: users, or should I use a different method for the social network of friends?

I am creating a small social network in Rails where people can add each other. I created a model called 'user'that contains, e-mail, a strong md5 hash with a salt of the password, etc.

How do I create something like an option to add another user as a friend? Is it possible to have something like has_many_and_belongs_to :userin a custom model? Thus, a user has many users and belongs to many users. Or should I use a different way, like adding a friendship model that has user1s_id:integerand user2s_id:integer?

+2
source share
3 answers

I would suggest that the user has many relationships, this will allow you to freely add new types of relationships in the future.

So, you start with the “one user to another user” relationship table (minimum, only two identifiers), and then in the future you can add the “one user to group” relationship table (after creating the groups Of course!)

+2
source

Essentially, you want a federated model to connect users to users. But for Rails, you have to use more descriptive terms.

Twitter Rails, , Rails, Twitter. . Twitter (.. , , , )

class User < ActiveRecord::Base
  has_many :followings
  has_many :followers, :through => :followings, :class_name => "User"
  has_many :followees, :through => :followings, :class_name => "User"
end


class Following < ActiveRecord::Base 
# fields: follower_id followee_id (person being followed)
  belongs_to :follower, :class_name => "User"
  belongs_to :followee, :class_name => "User"
end

(, Facebook , , ) . , SQL-. SQL , ActiveRecord, , .

+2

I would suggest using the friendship model, since db-wise you will need a connection table anyway, but with an explicit table I will store more detailed information about the relationship (for example, “friend” or “family”, date added, ...)

+2
source

All Articles