[英]Trying to delete comments in Rails
我正在嘗試通過構建一個簡單的博客來學習Rails。 在跟隨教程的同時,我使使用AJAX添加注釋成為可能。 但是,現在我正在嘗試刪除注釋,但它不起作用。 我不斷收到類似“沒有路線匹配[GET]“ / posts / 1 / comments / 3””的錯誤消息。
這些是我的路線:
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
這是我的routes.rb文件:
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 %>
和評論控制器:
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
謝謝你的幫助!
更新:我確實必須將'link_to'更改為'button_to',但是我在找到我必須解決的“破壞”操作中的評論時也犯了錯誤。
您正在嘗試使用comment_params
查找評論。
而不是在您的銷毀操作中使用@comment = @post.comments.find(comment_params)
,請嘗試使用@comment = Comment.find(params[:id])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.