In this chapter, we will complete the sample application by adding a social layer that allows users to follow (and unfollow) other users, resulting in each user’s Home page displaying a status feed of the followed users’ microposts.
The data model
As a first step toward constructing a data model for following users, let’s examine a typical case. For instance, consider a user who follows a second user: we could say that, e.g., Calvin is following Hobbes, and Hobbes is followed by Calvin, so that Calvin is the follower and Hobbes is followed.
We’ll use the generic term relationship for the table name, with a corresponding Relationship model. To get started with the implementation, we first generate a migration
Because we will be finding relationships by follower_id and by followed_id, we should add an index on each column for efficiency
To create the relationships table, we migrate the database as usual
Before implementing user following and followers, we first need to establish the association between users and relationships. A user has_many relationships, and—since relationships involve two users—a relationship belongs_to both a follower and a followed user.
Before moving on, we’ll add a couple of Relationship model validations for completeness.
The tests should be successful
Following and Followers
We come now to the heart of the Relationship associations: following and followers. Here we will use through for the first time: a user has many following through relationships
A test for following and followers
At this point, the full test suite should be successful