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

Rails, datepicker

= form_for @task do |f| = f.datetime_field :done_at = f.text_field I thought because done_at should be saved as DateTime, the field should be datetime_field. But text_field works fine. On top of that, for some browsers (Firefox, I can... Continue →