Reputation: 2842
I am trying to implement a has_and_belong_to_many
relation with the same model, but I don't know how.
For Example, a user should be able to follow other users.
Also, I have multiple fields of the same model in that model; how would I give it another name?
Upvotes: 0
Views: 105
Reputation: 75740
There are two scenarios and two different implementations:
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
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]
Upvotes: 1