railsのdestroyがうまくいきません。
削除ボタンでpostに紐づいているコメントを削除させようを思っているのですが、
No route matches {:action=>"show", :controller=>"comments", :id=>nil, :post_id=>"3"}, missing required keys: [:id]
というエラーメッセージが出てきます。
どうやらコメントのidが渡って来ないようで、ルーティングがうまくいってないようです。
どうすればidが渡ってくるようになるでしょうか?
HTMLとrouteとcontrollerは以下の通りです。
show.html.erb↓
<% @post.comments.each do |comment| %> <div class="comment"> <%= comment.body %> <%= link_to '削除', post_comment_path(@post, comment), #ここが間違ってる? method: :delete, class: 'x-btn', data: { confirm: 'Sure?' } %> </div> <% end %>
comments_controller.rb↓
def destroy @post = Post.find(params[:post_id]) @comment = @post.comments.find(params[:id]) @comment.destroy redirect_to("/posts/#{@post.id}") end
route↓
cloud9user:~/environment/myapp (master) $ rails routes Prefix Verb URI Pattern Controller#Action posts_index GET /posts/index(.:format) posts#index posts_new GET /posts/new(.:format) posts#new posts_create POST /posts/create(.:format) posts#create GET /posts/:id(.:format) posts#show GET /posts/:id/edit(.:format) posts#edit POST /posts/:id/update(.:format) posts#update POST /posts/:id/destroy(.:format) posts#destroy post_comments GET /posts/:post_id/comments(.:format) comments#index POST /posts/:post_id/comments(.:format) comments#create new_post_comment GET /posts/:post_id/comments/new(.:format) comments#new edit_post_comment GET /posts/:post_id/comments/:id/edit(.:format) comments#edit post_comment GET /posts/:post_id/comments/:id(.:format) comments#show PATCH /posts/:post_id/comments/:id(.:format) comments#update PUT /posts/:post_id/comments/:id(.:format) comments#update DELETE /posts/:post_id/comments/:id(.:format) comments#destroy posts GET /posts(.:format) posts#index POST /posts(.:format) posts#create new_post GET /posts/new(.:format) posts#new edit_post GET /posts/:id/edit(.:format) posts#edit post GET /posts/:id(.:format) posts#show PATCH /posts/:id(.:format) posts#update PUT /posts/:id(.:format) posts#update DELETE /posts/:id(.:format) posts#destroy
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。