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

ionic &amp; cordova setup

install ionic # sudo npm install -g ionic cordova sudo npm install -g ios-sim npm dependency.. start a project # ionic start myApp blank ionic start myApp tabs ionic start myApp sidemenu cd myApp run # ionic platform add ios ionic build... Continue →