Я не могу удалить комментарии из поста. Все остальное работает нормально. Я могу создавать комментарии, но каждый раз, когда я удаляю, я получаю сообщение об ошибке -Не могу найти комментарий с 'id' = 5 [WHERE "comments". "Post_id" =?] Мой код выглядит хорошо, насколько я могу судить. Я мог бы помочь, пожалуйста!
comments_controller
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(comment_params)
flash[:notice] = "Comment was created!"
redirect_to post_path(@post)
end
def destroy
@post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])
@comment.destroy
flash[:notice] = "Comment was deleted!"
redirect_to post_path
end
private
def comment_params
params.require(:comment).permit(:name, :body)
end
end
comment.html.erb
<div class="comment">
<p>
<strong>Comment Name:</strong><br>
<%= comment.name %>
</p>
<p>
<strong>Comment Body:</strong><br>
<%= comment.body %>
</p>
<%= link_to "Delete", [comment.post, comment], method: :delete, data: { confirm: "Are you sure?" } %>
</div>
routes.rb
Rails.application.routes.draw do
get "/pages/about", to: "pages#about", as: :about
get "pages/contact", to: "pages#contact", as: :contact
# get "/posts", to: "posts#index"
# post "/posts", to: "posts#create"
# get "/post/:id", to: "posts#show", as: :post
# patch "post/:id", to: "posts#update"
# delete "post/:id", to: "posts#destroy"
# get "/posts/new", to: "posts#new", as: :new_post
# get "/post/:id/edit", to: "posts#edit", as: :edit_post
resources :posts do
resources :comments, only: [:create, :destroy]
end
end
show.html.erb
<h1>Show page <%= link_to "Back", posts_path %></h1>
<p>
<%= @post.title %>
</p>
<p>
<%= @post.body %>
</p>
<%= link_to "Edit", edit_post_path(@post) %>
<%= link_to "Delete", post_path(@post), method: :delete, data: { confirm: "Are you sure?" } %>
<h2>All Comments: </h2>
<%= render @post.comments %>
<h2> Leave a Comment </h2>
<%= form_for [@post, @post.comments.build] do |f| %>
<%= f.label :name %><br>
<%= f.text_field :name %><br>
<%= f.label :body %><br>
<%= f.text_area :body %><br>
<%= f.submit %>
<% end %>
post_controller
class PostsController < ApplicationController
before_action :find_post, only: [:show, :edit, :update, :destroy]
def index
@posts = Post.all.order("created_at DESC")
end
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
if @post.save
flash[:notice] = "Post was successfully created!"
redirect_to post_path(@post)
else
render :new
end
end
def show
end
def edit
end
def update
if@post.update(post_params)
flash[:notice] = "Post was updated!"
redirect_to post_path(@post)
else
render :edit
end
end
def destroy
@post.destroy
flash[:notice] = "Post was deleted!"
redirect_to posts_path
end
private
def find_post
@post = Post.find(params[:id])
end
def post_params
params.require(:post).permit(:title, :body)
end
end