Put comments under a post

How-to from “just a post” to “a post with comments under it” page.

We will have:

We need:

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!

 
1
Kudos
 
1
Kudos

Now read this

Git Merge your next Change

Sometimes when you want to merge changes made in another branch (in some remote) to your master branch. (or any branch supposed to be working) When you trust and it works fine for sure, then it would be quite simple: git merge And also... Continue →