ruby on railsでいいね機能を作成しようと思っているのですが,show.html.erbのいいねされていませんのリンクを押すと
下記のrootのエラーが起きてしまいます
No route matches [POST] "/posts/likes/6/create"
なぜ"/posts/likes/6/create"になってしまうのかわかりません.本来は"likes/:post_id/create"のような表示になるはずなのですが...
いろいろ試してみましたが,うまくいきません
どなたかご享受お願いいたします
#show.html.erb <div class="main posts-show"> <div class="container"> <p> <%= @post.content %> </p> <div class="post-time"> <%= @post.created_at %> </div> <% if Like.find_by(user_id: current_user.id, post_id: @post.id) %> <%= link_to("likes/#{@post.id}/destroy", {method: "post"}) do %> <span class="fa fa-heart like-btn-unlike">いいね</span> <% end %> <% else %> <%= link_to("likes/#{@post.id}/create", {method: "post"}) do %> <span class="fa fa-heart like-btn">いいねされてません</span> <% end %> <% end %> <% if @post.user_id == current_user.id %> <div class="post-menus"> <%= link_to("投稿を編集","/posts/#{@post.id}/edit") %> <%= link_to("削除", "/posts/#{@post.id}/destroy", {method: "post"}) %> </div> <% end %> </div> </div>
#routes.rb Rails.application.routes.draw do devise_for :users, controllers: { omniauth_callbacks: 'users/omniauth_callbacks'} post "likes/:post_id/create" => "likes#create" post "likes/:post_id/destroy" => "likes#destroy" get 'posts/index' => "posts#index" get 'posts/new' => "posts#new" get "posts/:id" => "posts#show" post 'posts/create' => "posts#create" get "posts/:id/edit" => "posts#edit" post "posts/:id/update" => "posts#update" post "posts/:id/destroy" => "posts#destroy" get "/" => "home#top" # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end
#likes_controller.rb class LikesController < ApplicationController before_action :authenticate_user! def create @like = Like.new(user_id: current_user.id, post_id: params[:post_id]) @like.save redirect_to("/posts/#{params[:post_id]}") end def destroy @like = Like.find_by(post_id: params[:post_id],user_id: current_user.id) @like.destroy redirect_to("/posts/#{params[:post_id]}") end end
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。