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

Authorization with Pundit

I want share my experience in the group from our Monday meetup yesterday. Let’s refresh the memory: “do authorization with pundit gem” – Homework here on github issue #12 https://rubygems.org/gems/pundit We went to this page and bundle... Continue →