2016-08-14 48 views
1

我目前正試圖刪除評論,完全相同的方式我可以在我的應用程序中刪除一篇文章。然而,出於某種原因完全相同的代碼似乎並沒有對我的評論工作的回報以下錯誤: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 

這是我在我看來鏈接看起來像(超薄):

- @comments.each do |comment| 
     .comment-container.level-0 
     p 
     a href="https://stackoverflow.com/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

'耙路線的輸出是什麼| grep comments'命令? – Emu

+0

comments POST /comments(.:format)comments#create comment DELETE /comments/:id(.:format)comments#destroy – patrick

+0

@patrick你可以在你的routes.rb文件中發佈代碼嗎? –

回答

2

我猜你只是錯過了link_to方法的格式:

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

它應該是這樣的:link_to(body, url, html_options = {}) 你錯過了正文部分。

檢查here

編輯

I just realised that when I posted this comment: If I try this, then the error is: undefined method `post' for nil: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 

然後你會好到哪裏去。 :)

+0

不幸的是,仍然得到相同的錯誤。 – patrick

+0

這個'@ comment'變量來自哪裏?這是一個單獨的'Comment'對象還是一堆對象? – Emu

+0

此鏈接位於以下循環中: - @ comments.each do | comment | – patrick

相關問題