2016-08-14 13 views
1

私は現在、アプリケーションと同じ方法でコメントを削除しようとしています。しかし、何らかの理由でまったく同じコードが戻って私のコメントを次のエラー動作していないよう:Rails 5エラー:[DELETE] "/ comments"と一致するルートはありません

Noルートの一致をこれがどのような私です「/コメント」

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

'rake routes |の出力は何ですか? grep comments'コマンド? – Emu

+0

コメントPOST /comments(.:format)comments#create コメントDELETE /comments/:id(.:format)comments#destroy – patrick

+0

@patrick routes.rbファイルにコードを投稿できますか? –

答えて

2

私はあなただけlink_toメソッドの形式を逃した推測:link_to(body, url, html_options = {}) ます:

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

それはようにする必要があります本体部分が見つかりませんでした。

チェックhere

EDIT

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

[OK]を、問題がある:あなたはそれがdestroy方法に行くのリンクをクリックすると。次に、@post = @comment.postのようなクエリを試みます。リンクに表示されているとおり、commentを送信しています。そして、あなたが行ってもいいでしょう

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 

:だから破壊する方法であなたは次のようにpostをフェッチする必要があります。 :)

+0

残念ながら、まったく同じエラーが表示されます。 – patrick

+0

この '@ comment'変数はどこから来ましたか?これは単一の 'Comment'オブジェクトか複数のオブジェクトですか? – Emu

+0

このリンクは次のループ内にあります: - @ comments.each do | comment | – patrick

関連する問題