Put comments under a post
How-to from “just a post” to “a post with comments under it” page.
We will have:
- comment creation form in the post show page
- list of all comments after.
We need:
- nested resources (need routing supports that generated url)
- model-backed form of comment object
- action in controller (create action)
- rendering validation errors of it.
put a (resourceful) routing for comments
resources :posts do
resources :comments, only: :create
end
and it has now URL
<form action="/posts/:id/comments" method="post">
and params from the form
params
=> { ...
"comment"=>{"body"=>"this is a comment"},
"commit"=>"Create Comment",
"controller"=>"comments",
"action"=>"create",
"post_id"=>"6"}
so now we change posts_controller show action
@comment = Comment.new
and comments_controller create action like,
@comment = Comment.new(params.require(:comment).permit(:body))
@post = Post.find(params[:post_id])
However, in this case we need require in it. When it’s an invalid key, without require, the hash returns different results.
params[:post_id]
=> "6"
params[:comment]
=> {"body"=>"this is a comment"}
params.require(:comment).permit(:body)
=> {"body"=>"this is a comment"}
“need to associate this @comment to that @post to make show up on the list.”
@comment.post = @post
Here’s alternative for these three lines, it doesn’t have to be build, instead of new though.
@post = Post.find(params[:post_id])
@comment = @post.comments.build(params.require(:comment).permit(:body))
Bye!