When you try to delete a comment, the following error is displayed:

ActiveRecord :: RecordNotFound in PostsController # destroy
Couldn't find Post with 'id' = <Comment :: ActiveRecord_Associations_CollectionProxy: 0x00007f67f0090ce0>
Extracted source (around line # 39):
def destroy @post = Post.find (params [: id])
@ post.destroy redirect_to posts_path

My code is:

class CommentsController < ApplicationController def destroy @post.comments= Post.find(params[:post_id]) @post.comments.destroy redirect_to posts_path(@post) end end # routes.rb Rails.application.routes.draw do root 'posts#index', as: 'home' resources :posts do resources :comments end end # posts/show.html.erb <h1><%=@post.title %> </h1> <p><%=@post.body %></p> <p> <%= image_tag @post.image.url(:thumb), class: 'img-show' if @post.image? %> </p> <hr> <%= link_to "Редактировать", edit_post_path(@post), :class=> 'btn btn-warning' %> <%= link_to "Удалить пост", post_path(@post), method: :delete, data: {confirm:"Вы хотите удалить статью ?"}, :class => 'btn btn-danger'%> <h2>Вcе коментарии</h2> <% @post.comments.each do |comments| %> <div class="alert alert-light"> <p><strong><%=comments.username%></strong>: <%=comments.body%></p> </div> <% end %> <h2>Коментарии</h2> <%=form_for([@post, @post.comments.build]) do |f| %> <p> Пользователь<br> <%=f.text_field(:username)%> </p> <p> Текст комментария<br> <%= f.text_area(:body)%> </p> <p> <%= f.submit("Добавить Коментарий")%> </p> <% end %> <%= link_to "Удалить Комент ", post_path(@post.comments), method: :delete, data: {confirm:"Вы хотите удалить?"}, :class => 'btn btn-danger'%> 
  • Do you understand what you write in the code? Look again at your code, please. - Colibri

1 answer 1

Let's try to figure it out. Judging by your question, you want to delete only one comment. Judging by your controller code, you want to delete all comments at once. Looking at your form code, I don’t take any chances to draw conclusions ... So, in the controller:

 def destroy # тут вы пытаетесь назначить неопределённому ещё @post сущность той же модели Post # в качестве комментариев. @post.comments= Post.find(params[:post_id]) # тут же пытаетесь это всё удалить, но работать оно не будет, # для удаления ассоциации нужно использовать destroy_all @post.comments.destroy # тут вы видимо хотели вернуться к этому же посту, но написали лишнюю s в роуте redirect_to posts_path(@post) end 

I believe that you still want to delete one specific comment, then it should be:

 def destroy @post = Post.find(params[:post_id]) @post.comments.find(params[:id]).destroy redirect_to post_path(@post) end 

Link in the view <%= link_to "Удалить Комент", post_path(@post.comments) ... %> tries to go where it’s not at all clear. post_path is a route to a specific post, but it needs an ID of this post itself, you send the comment association instead. How it should look like - the display of all comments on the post, and each has a link to delete:

 <h2>Вcе коментарии</h2> # обратите внимание на название внутренней переменной, она в единственном числе, # потому как в каждой итерации мы имеем дело с одним комментом <% @post.comments.each do |comment| %> <div class="alert alert-light"> <p><strong><%=comment.username%></strong>: <%=comment.body%></p> </div> <%= link_to "Удалить Коммент", post_comment_path(@post, comment), method: :delete, data: { confirm: "Вы хотите удалить?" }, :class => 'btn btn-danger'%> <% end %> 

UPDATE:

I didn’t see right away, I fixed posts_path(@post) on post_path(@post) in a redirect. posts_path is the route to the index action in the controller, and you need the route to the show

I highly recommend it to you - before continuing the project, carefully read the chapters on Models, Views and Controllers in the guide

  • Thank you) but here is another question, after deleting the koment, it throws me to the main page, but how to make it so that after deletion, koment, we stay on the post page? - Alexander Lin
  • @AleksandrLin, updated the answer, look - Vasilisa