Search code examples
ruby-on-rails-3activerecordmodel-associations

Rails: how to represent user follow user relationship?


I have a class User and I would like to implement the follow relation (as in twitter). In my model a user can follow a set of other users, and also can be followed by a set of users.

In the database, there are two tables: User and Follow.

Follow has src_id and dst_id, both foreign keys to the User table. An entry in the follow table means that user with id=src_id is following user with id=dst_id.

I am having difficulty expressing this in the actual models... thanks!


Solution

  • This should be what you're looking for: http://ruby.railstutorial.org/book/ruby-on-rails-tutorial#cha-following_users

    For a more expansive friendship model where users can request to be friends, show pending friends etc. you could try this gem https://github.com/raw1z/amistad and this is a really good tutorial on how to get it working: http://keighl.com/post/amistad-friendships-controller

    Hope that helps!