railsでいいね機能の非同期化したいです。
indexの方ではエラーが出ないのですが、user showの方で以下のエラーが出ます。ネットで検索してルーティングの確認をしたり、book.idが空になっているのでおそらくコントローラーに問題があると思い、引数を変えてみましたが解決しません。
どこをなおしたら良いかわかりません。
また、見づらい部分もあるかもしれませんがよろしくお願いします。
ActionController::UrlGenerationError in Users#show
Showing /home/ec2-user/environment/rails6-bookers2-debug-ruby3-main/app/views/favorites/_favorite.html.erb where line #7 raised:
No route matches {:action=>"destroy", :book_id=>nil, :controller=>"favorites"}, missing required keys: [:book_id]
Extracted source (around line #7):
5
6
7
8
9
10
<% end %>
<% else %>
<%= link_to book_favorites_path(book), method: :post, remote: true,data: {"turbolinks" => false} do %>
<i class="fas fa-heart" ></i>
<%= book.favorites.count %>
<% end %>
Trace of template inclusion: #<ActionView::Template app/views/books/_index.html.erb locals=["books"]>, #<ActionView::Template app/views/users/show.html.erb locals=[]>
gem 'jquery-rails'を導入しています。
該当していると思われるコードを記載します。
class FavoritesController < ApplicationController
before_action :authenticate_user!
#belongs_to :user
#sbelongs_to :book
def create
@book = Book.find(params[:book_id])
favorite = current_user.favorites.new(book_id: @book.id)
favorite.save
#redirect_to books_path
end
def destroy
@book = Book.find(params[:book_id])
favorite = current_user.favorites.find_by(book_id: @book.id)
favorite.destroy
#redirect_to books_path
end
end
_favorite.html
<% if book.favorited_by?(current_user) %>
<%= link_to book_favorites_path(book), method: :delete, remote: true, data: {"turbolinks" => false} do %>
<i class="fas fa-heart", style="color:red;" ></i>
<%= book.favorites.count %>
<% end %>
<% else %>
<%= link_to book_favorites_path(book), method: :post, remote: true,data: {"turbolinks" => false} do %>
<i class="fas fa-heart" ></i>
<%= book.favorites.count %>
<% end %>
<% end %>
create.js
$('#favorite_buttons_<%= @book.id %>').html("<%= j(render "favorites/favorite", book: @book) %>");
destroy.js
$('#favorite_buttons_<%= @book.id %>').html("<%= j(render "favorites/favorite", book: @book) %>");
assets/javascript/application.js
//= require jquery
//= require rails-ujs
routes.rb
Rails.application.routes.draw do
devise_for :users
root to: "homes#top"
get 'home/about'=>'homes#about', as: 'about'
post 'books' => 'books#create'
resources :books, only: [:index,:show,:edit,:create,:destroy,:update,:new] do
resource :favorites, only: [:create, :destroy]
resources :book_comments, only: [:create, :destroy]
end
resources :users, only: [:index,:show,:edit,:update]
get 'search' => 'searches#search'
resources :users do
resource :relationships, only: [:create, :destroy]
get 'followings' => 'relationships#followings', as: 'followings'
get 'followers' => 'relationships#followers' , as: 'followers'
end
#get 'search' => 'searches#search'
end