user2911232
user2911232

Reputation:

Editing a comment that belongs to a post

So I have created a blog that users can create posts and others can comment on that post.

I want users to be able to edit the comments.

What I did so far is the following:

My routes are like this:

  resources :posts do
    resources :comments
  end

and when I rake route I get this:

new_post_comment GET    /posts/:post_id/comments/new(.:format)      comments#new
edit_post_comment GET   /posts/:post_id/comments/:id/edit(.:format) comments#edit
post_comment GET        /posts/:post_id/comments/:id(.:format)      comments#show

on my view file I use this which is obviously wrong

  <%= link_to 'Edit Comment', edit_post_comment_path(@comment) %>

and my controller is like that:

  def edit
    @post = Post.find(params[:post_id])
    @comment = @post.comments.find(params[:id])
  end

   def update
    @post = Post.find(params[:post_id])
    @comment = @post.comments.find(params[:id])

    if @comment.update(comments_params)
      redirect_to post_path(@post)
    else
      render 'edit'
    end
  end

When I try to visit the page (of the post) I get this error:

No route matches {:action=>"edit", :controller=>"comments", :id=>nil, :post_id=>nil, :format=>nil} missing required keys: [:post_id, :id]

That's the first time I work on nested routes. I read some tutorials but had nothing really helped me to fix this. I am not sure how can I pass these keys...

(if you need any other info please let me know and I will provide them)

Any help is greatly appreciated!

Upvotes: 2

Views: 2281

Answers (1)

Simone Carletti
Simone Carletti

Reputation: 176442

You need to pass both the @post and @comment instance.

edit_post_comment_path(@post, @comment)

Generally speaking, you need to pass every instance matching the resource the route is part of. So, in a single route like

edit_post_path(@post)

you pass only the post. In a post/comment nested route you pass both. In a post/comment/whatever you will need to pass the three resources, etc.

Upvotes: 4

Related Questions