There are a few ways you can create a twitter-like-followers feature with rails and mongo. You can create an entire collection to hold all your relationships of followers by their ids. You could also create a has_many relationship between a Follow model. I didn’t like these solutions. I didn’t feel like the ruby way nor the mongo way.
I wanted a simple solution of:
User A needs to follow User B
User B needs to have User A as their follower
Store in the same User document as follower_ids and following_ids
Now, we should be able to pull back my user from our API (using Grape) and it should contain all the user ids i’m following and the user ids that are following me. Simple stupid.
Add has_and_belongs_to_many relationship to your User model
Add methods to help us follow and unfollow users
Add endpoint on your API to make this accessible
That should do it. As soon as you follow a user. A bunch of magic happens and you’re left with an array populated on your user.
Tweet me if you have questions!
A collection of software development, thoughts, and vices.