前提・実現したいこと
rails6 でSNSを製作中、いいね機能をajaxで非同期で実装しようとしています。
いいねのフォームはbook(投稿)のshowページにあるのですが、いいねをすでにしている状態でbookのshowページに戻ると、すでにしてあるいいねのidを見つけられずに、以下のエラーが出てしまいます。
発生している問題・エラーメッセージ
ActionView::Template::Error (No route matches {:action=>"destroy", :book_id=>"301", :controller=>"likes", :id=>nil}, missing required keys: [:id]): 1: <%= form_with(url: book_like_path(@book, @like), html: { method: :delete }, remote: true) do |f| %> 2: <%= f.submit "いいねを取り消す", class: "btn" %> 3: <% end %>
該当のソースコード
usersコントローラ
def show @user = User.find(params[:id]) @books = @user.books.paginate(page: params[:page]) @like = Like.new end
booksコントローラ
def show @book = Book.find(params[:id]) @like = Like.new @comments = @book.comments @comment = Comment.new end
likesコントローラ
class LikesController < ApplicationController def create @book = Book.find(params[:book_id]) @like = current_user.likes.create(book_id: params[:book_id]) respond_to do |format| format.html { redirect_to @book } format.js end end def destroy @book = Book.find(params[:book_id]) @like = Like.find_by(book_id: params[:book_id], user_id: current_user.id) @like.destroy respond_to do |format| format.html { redirect_to @book } format.js end end end
books/show.html.erb
<div class="liked_users"> <div id="like_form"> <% if current_user.already_liked?(@book) %> <%= render 'likes/unlike' %> <% else %> <%= render 'likes/like' %> <% end %> </div> <p> いいね <strong id="likes_count"> <%= @book.likes.count %> </strong> 件 </p> <div id="liked_by"> <%= render 'liked_users' %> </div>
likes/_like.html.erb
<%= form_with(url: book_likes_path(@book), remote: true) do |f| %> <%= f.submit "いいね", class: "btn" %> <% end %>
likes/_unlike.html.erb
<%= form_with(url: book_like_path(@book, @like), html: { method: :delete }, remote: true) do |f| %> <%= f.submit "いいねを取り消す", class: "btn" %> <% end %>
likes/create.js.erb
$("#like_form").html("<%= escape_javascript(render('likes/unlike')) %>"); $("#likes_count").html('<%= @book.likes.count %>'); $("#liked_by").html("<%= escape_javascript(render('books/liked_users')) %>");
likes/destroy.js.erb
$("#like_form").html("<%= escape_javascript(render('likes/like')) %>"); $("#likes_count").html('<%= @book.likes.count %>'); $("#liked_by").html("<%= escape_javascript(render('books/liked_users')) %>");
Like model
class Like < ApplicationRecord belongs_to :book belongs_to :user validates_uniqueness_of :book_id, scope: :user_id end
※追記
routes.rb
Rails.application.routes.draw do root 'static_pages#home' get '/home', to: 'static_pages#home' get '/help', to: 'static_pages#help' get '/signup', to: 'users#new' get '/login', to: 'sessions#new' post '/login', to: 'sessions#create' delete '/logout', to: 'sessions#destroy' resources :users do member do get :following, :followers end end resources :books, only: [:show, :create, :destroy] do resources :likes, only: [:create, :destroy] resources :comments, only: [:create] end resources :relationships, only: [:create, :destroy] end
回答1件
あなたの回答
tips
プレビュー