Rails 5 error: No route matches [DELETE] "/comments"

Rails 5 error: No route matches [DELETE] "/comments"

我目前正在尝试删除评论,就像我在应用程序中删除 post 一样。但是,出于某种原因,完全相同的代码似乎不适用于我的评论 returns 以下错误:

没有路由匹配 [DELETE] "/comments"

def destroy
   @post = @comment.post
   @comment.destroy
   respond_to do |format|
      format.html { redirect_to @post, notice: 'Comment was successfully destroyed.' }
      format.json { head :no_content }
   end
end

这是我的模型的样子:

class Comment < ApplicationRecord
    belongs_to :post
    belongs_to :user
end

这是我的路线:

Rails.application.routes.draw do
   resources :posts
   resources :users
   resources :comments, only: [:create, :destroy]

   #signup and register workflow
   get '/signup' => 'users#new'
   get '/login' => 'sessions#new'
   post '/login' => 'sessions#create'
   delete '/logout' => 'sessions#destroy'
end

这就是我 link 在我看来的样子(苗条):

   - @comments.each do |comment|
      .comment-container.level-0
        p 
        a href="/users/#{comment.user_id}" = comment.user.first_name
        | : 
        = comment.comment
        - if comment.user == current_user
          .icon-delete
            = link_to "Delete", comment, method: :delete, data: { confirm: 'Are you sure?' }
    end
    hr
    h3 Write a new comment
    = bootstrap_form_for(@comment) do |c|
      .field
        = c.text_field :comment
      .field
        = c.hidden_field :user_id, :value => current_user.id
        = c.hidden_field :post_id, :value => @post.id
      .actions
        = c.submit

我猜你只是错过了 link_to 方法的格式:

= link_to "Delete", comment, method: :delete, data: { confirm: 'Are you sure?' }

应该是这样的:link_to(body, url, html_options = {}) 您错过了 body 部分。

勾选here

编辑

I just realised that when I posted this comment: If I try this, then the error is: undefined method `post' for nil:NilClass

好的,问题是:当您单击 link 时,它会转到 destroy 方法。然后它会尝试查询 @post = @comment.post。正如您在 link 中看到的,您正在发送 comment。所以在 destroy 方法中,你应该像这样获取 post

def destroy
   @comment = Comment.find(params[:id])
   @post = @comment.post
   @comment.destroy
   respond_to do |format|
      format.html { redirect_to @post, notice: 'Comment was successfully destroyed.' }
      format.json { head :no_content }
   end
end

那你就可以开始了。 :)