Intro
In this section we are going to dive deep into database migration.
Create new table
We use the model Bond to indicate a connection between one user and another. It has the state field to indicate the state of the connection.
Schema
Schema of Bound
Column | Data Type | Options |
---|---|---|
id | int |
Primary key, non-null |
user_id | int |
Foreign key(users), non-null |
friend_id | int |
Foreign key(users), non-null |
state | string |
Non-null |
Possible value of state
State | Description |
---|---|
requesting | When a user sends a follow request to another user (which will be accepted automatically if it is a public account) |
following | When a user is following another user |
blocking | When a user is blocked another user |
Generate Migration File
Command to scaffold Bond
|
|
Modify Migration File
After that, let’s enforce non-null constraints as shown below
|
|
Next, let’s make user_id and friend_id a unique combination. This way, there is no way the table can have multiple bond records between the same user A and the same user B for those fields, respectively.
|
|
As we have bonds.user_id
and bonds.friend_id
referencing users.id
, we add a foreign key for each of them in line 3 and 4.
Schema Statement
https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html