Episode completed

Next epsiode starting in 3 seconds

Published at


A blog without a comment section is like a car without wheels. To add comments, we need to add a table for them in the schema editor. Comments, like everything, need an id. Further than that, we need a postId, which stores the id of the post you add the comment to. This is needed to check which comment is from which blog post. We also need text fields for the author and the body. After setting up the table, we can create a controller for the comments. Next, we can add an add comment button to the end of a blog post show view. If we now try to use that, we have to input the postId manually.

To get the postId automatically, we need to change the new comment action a bit. First we need to adjust the type of the new comment action in the types file. If we pass the id of the post when creating a comment, the action can save the id without having to input it manually.

Next we need to tell the controller what to do with the postId. We need to define the postId in the action definition to use it. Now we can set the postId for the newComment. Now, the postId is automatically added, but the user doesn’t need to see or edit that, so let’s go into the new comment view and make the postId field hidden.

Now we can create comments, but we can’t see them. To fix this, we can just get the comments of a post in the show post view. But before that works, we need the post to include its comments by adding that to the type. To meet that requirement, we need to add this fetch related statement which fetches all comments with the postId of the post. To display them nicely, we need a renderCommentFunction which takes a comment and displays it in Html. This function can be called for each comment we get from the post. Before we test this, let’s also add the title of the post the comment is written for to the new comment view. To do that, we can simply fetch the post with the postId we get and pass that to the new comment view.

We also need to fetch this here, since the new view will need a post object in every case.

Here we can use the post to get its title in the headline of the new comment view. Now, we can create comments, which are displayed below a blog post.