如何删除嵌套对象?

How to delete a nested object?

我创建了一个博客,其中包含文章和评论。我想创建一个选项,这样我也可以删除评论,但是当我单击删除按钮时,错误显示 "Couldn't find Comment with 'id'=#id here"

resources :articles do
    resources :comments
end

查看

<div>
<h4>Comment by <%= comment.author_name %></h4>
<p><%= comment.body %></p>
</div>
<p> <%= link_to "Delete Comment", article_comment_path(@comment.article_id, @comment.article.id), method: :delete %> </p>

评论控制器

def destroy
    @comment = Comment.find(params[:id])
    @comment.destroy

    redirect_to article_path(@comment.article)
end

您正在引用与 ... @comment.article_id, @comment.article.id ... 相同的文章对象。试试这个:

<%= link_to "Delete Comment", article_comment_path(@comment.article, @comment), method: :delete %>

编辑

我现在看到您还试图在 @comment 对象被销毁后引用它。

def destroy
    @article = Article.find(params[:article_id])
    @comment = Comment.find(params[:id])
    @comment.destroy

    redirect_to article_path(@article)
end