There are two scenarios and two different implementations:
The 'Friends' model
Let's say one User
can have many :friends
where each friend is also an object of the User
model. You can do it this way:
has_and_belongs_to_many :friends, class_name: 'User'
This tells rails that an object of User
class can have a many-to-many relation with itself as friends
. So you can call something like this:
@user_a.friends
#=> [@user_x, @user_y, @user_z] # Array of User Objects
@user_x.friends
#=> [@user_a, @user_b, @user_c] # Array of User Objects
The 'Followers/Following' model
Let's say one User
can follow other users as well have other users follow him. This is how you'll implement it:
has_many :followers, class_name: 'User', inverse_of: :following
belongs_to :following, class_name: 'User', inverse_of: :followers
This tells rails that each user can have many followers
which is an Array of other User
objects, and that user is accessible to others as an object in the following
array. For example, if @user2
follows @user1
, it would look like this:
@user1.followers
#=> [@user2, @user3]
@user2.following
#=> [@user1]