0

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?

Sheharyar
  • 73,588
  • 21
  • 168
  • 215
Gardezi
  • 2,692
  • 2
  • 32
  • 62

1 Answers1

1

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]
Sheharyar
  • 73,588
  • 21
  • 168
  • 215
  • I always got stuck with `inverse_of` options... can you clarify what it does ? – Arup Rakshit May 25 '15 at 11:09
  • 1
    +1 for more details. Still what technically `inverse_of` option does there? Anything kind of _caching_... ? Got the answer, it is [optimization](http://stackoverflow.com/questions/9296694/what-does-inverse-of-do-what-sql-does-it-generate). – Arup Rakshit May 25 '15 at 11:22
  • Why don't need to mention _foreign_key_ here ? – Arup Rakshit May 25 '15 at 11:23
  • Multiple ways of doing the same thing... We don't need to specify it _explicitly_ here, since we're already using `inverse_of`. If we use `foreign_key` instead, we'll have to change `following` to `following_ids`. I think the `inverse_of` approach looks cleaner. – Sheharyar May 25 '15 at 12:21
  • RoR [Associations Guide](http://guides.rubyonrails.org/association_basics.html) has a lot more information on this. – Sheharyar May 25 '15 at 12:23
  • I read the guide. But it looks experienced eyes sometime to understand what they meant.. I am away now from those eyes.. anyway thanks for those replies... – Arup Rakshit May 25 '15 at 12:33