Comments Structure
Set up your comments model.
The next step for your app is to handle user comments. For this, you will need to set up a Comment
model similar to what you did for Link
.
You will run the following to generate the scaffolding for your Comment
model.
rails g scaffold Comment body:text link_id:integer:index user:references
Running this command will generate a migration file db/migrate/<date_time>_create_comments.rb
with the following content:
class CreateComments < ActiveRecord::Migration[5.2]
def change
create_table :comments do |t|
t.text :body
t.integer :link_id
t.references :user, foreign_key: true
t.timestamps
end
add_index :comments, :link_id
end
end
user:references
creates a new column in our database with _id
appended to the end of the provided model name (user
). In this file t.references
creates a user_id
column, a foreign key that points to the id
of the user
, and an index
for it (recall
This will allow you to use commands such as @comment.user
to get the user who made a certain comment. All methods associated with user
can be accessed through this once you create the associations.
the add_index
line is similar to what you did for links
and user_id
. It will allow access to commands such as @comment.link
as well as @link.comments
after creating the appropriate associations.
Note:
:references
and:index
both create an index in the table.:references
was not used forlinks
for the purpose of the upcoming challenge. You can visit thedb/schema.rb
file to get an understanding of the current database schema and of the indexes we have created.
Along with the migration file, the usual controller and view structure are also generated.
Get hands-on with 1400+ tech skills courses.