I am trying to learn Rails by building a simple blog. Following along with a tutorial, I have made it possible to add comments with AJAX. However, now I'm trying to make deleting the comments possible and it doesn't work. I keep getting error messages like "No route matches [GET] "/posts/1/comments/3"".
These are my routes:
post_comments_path POST /posts/:post_id/comments(.:format) comments#create
post_comment_path DELETE /posts/:post_id/comments/:id(.:format) comments#destroy
posts_path GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
new_post_path GET /posts/new(.:format) posts#new
edit_post_path GET /posts/:id/edit(.:format) posts#edit
post_path GET /posts/:id(.:format) posts#show
PATCH /posts/:id(.:format) posts#update
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy
root_path GET / posts#index
This is my routes.rb file:
Rails.application.routes.draw do
resources :posts do
resources :comments, only: [:create, :destroy]
end
root 'posts#index'
end
_comment.html.erb:
<%= div_for comment do %>
<p>
<strong>
Posted <%= time_ago_in_words(comment.created_at) %> ago
</strong>
<br/>
<%= comment.body %>
</p>
<p>
<%= link_to 'Delete', [comment.post, comment],
:method => :delete,
data: { confirm: 'Are you sure?' }
%>
</p>
<% end %>
And the comments controller:
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create!(comment_params)
respond_to do |format|
format.html { redirect_to @post }
format.js
end
end
def destroy
@post = Post.find(params[:post_id])
@comment = @post.comments.find(comment_params)
@comment.destroy
respond_to do |format|
format.html { redirect_to @post }
format.js
end
end
private
def comment_params
params.require(:comment).permit(:body)
end
end
Thanks for your help!
Update: I did have to change 'link_to' to 'button_to', but I also had in mistake in finding my comment in the 'destroy'-action which I had to fix.