We're going to add another feature to our blog app: the ability to comment on a post.
- Rails Blog Scaffold
- Rails Blog Associations Validations
- Rails Blog Nested Forms
NOTE: As with much of our Rails curriculum, remember to always use the --no-test-framework
flag when you generate models, controllers, etc. That way, the Rails generators will not create additional tests on top of the test suite that already comes with the lesson. E.g., rails g model User username:string email:string --no-test-framework
.
-
Generate a model for Comment.
-
Associate comment and post and user, making the appropriate migration changes.
-
Let's create some validations on comment; content should always be present.
-
Generate a controller for comment. We only need a
create
action, because viewing comments will be handled on the posts show page. Be sure to permit appropriate params in a private method. -
Comments will be a resource nested under posts. Why? Logically, comments only matter when they are associated with a post.
-
Get the model tests to pass.
Check out the documentation on Nested Resources.
-
Edit the show page for a post to include all comments for the post.
-
On the post show page, we want to have a form to submit a comment. Build out a form for that takes an array as a parameter, and has a hidden field to handle the
post_id
. -
Get the comment features tests to pass.
View Rails Blog: Comments on Learn.co and start learning to code for free.