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
db/migrate/[timestamp]_create_relationships.js
To create the relationships table, we migrate the database as usual
User/relationship associations
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.
app/models/user.js
app/models/relationship.js
Relationship validations
Before moving on, we’ll add a couple of Relationship model validations for completeness.
test/models/relationship_test.js
app/models/relationship.js
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
app/models/user.js
A test for following and followers
test/models/user_test.js
At this point, the full test suite should be successful