Rails 5错误:没有路由匹配[DELETE]" / comments"

时间:2016-08-14 04:57:45

标签: ruby-on-rails ruby-on-rails-4 ruby-on-rails-5

我目前正在尝试删除评论的方式与我在应用程序中删除帖子的方式完全相同。但是,由于某些原因,完全相同的代码似乎不适用于我的注释,返回以下错误:

没有路线匹配[删除]" /评论"

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

这是我视图中的链接(Slim):

   - @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

1 个答案:

答案 0 :(得分:2)

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

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

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

检查here

修改

  

我刚刚意识到,当我发表此评论时:如果我试试这个,那么   错误是:nil的未定义方法`post':NilClass

好的,问题是:当您点击链接时,它会转到destroy方法。然后它尝试查询@post = @comment.post。正如您在发送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

然后你会好起来的。 :)