我目前正在遵循基本的Rails指南来创建博客,但是在删除与该帖子相关的comments
时遇到了麻烦。
这里是我的评论控制者:
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(params[:comment].permit(:commenter, :body))
redirect_to post_path(@post)
end
def destroy
@post = Post.find params[:post_id]
@comment = @post.comments.find params[:id]
@comment.destroy
redirect_to post_path(@post)
end
end
在我看来,destroy
操作根本没有触发。因此,我什至无法使用控制台作为解决问题的工具。
这里是comments
的部分视图:
h2 Comments
- @post.comments.each do |comment|
p
strong Commenter:
= comment.commenter
p
strong Comment:
= comment.body
p = link_to "Delete Comment", [comment.post, comment],
method: :delete,
data: { confirm: 'Are you sure?' }
生成用于删除链接的html:
<a data-confirm="Are you sure?" data-method="delete" href="/posts/9/comments/2"
rel="nofollow">Delete Comment</a>
即使我对帖子的销毁操作也没有发出任何请求,这使我认为问题可能出在我移至局部文件时。
在控制台内,我仍然可以通过按post_id
查找帖子,然后找到与该帖子关联的评论并销毁它来删除评论。由于某些原因,我无法弄清楚为什么视图链接不会执行任何操作。
请首先确保在模板中放置正确的缩进,否则可能会弄乱东西。带有锚链接的最后一段似乎输入有误:
h2 Comments
- @post.comments.each do |comment|
p
strong Commenter:
= comment.commenter
p
strong Comment:
= comment.body
p
= link_to "Delete Comment", [comment.post, comment], method: :delete, data: { confirm: 'Are you sure?' }
然后,您应该查看rails服务器日志,以查看单击链接时发生的情况。如果HTML链接看起来不错,则可以对服务器must进行调用,其中包含调试调用所需的所有信息。
@post = Post.find(params[:id])
@comment = @post.comments.where(post_id: @post.id)
@comment.each do |comment|
comment.destroy
end