前提・実現したいこと
現在本のレビューSNSのようなシステムを作っています。
非同期通信機能を実装中にターミナル内に以下のエラーメッセージが発生しました。
自身でもいろいろ試したのですがいまいち上手くいかずご教授の方をよろしくお願いします。
発生している問題・エラーメッセージ
NoMethodError (undefined method `destroy' for nil:NilClass):
app/controllers/favorites_controller.rb:15:in `destroy'
Started DELETE "/books/25/favorite" for 133.200.42.129 at 2021-10-07 13:15:45 +0000
Cannot render console from 133.200.42.129! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by FavoritesController#destroy as JS
Parameters: {"book_id"=>"25"}
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 13], ["LIMIT", 1]]
↳ /home/ec2-user/.rvm/gems/ruby-2.6.3/gems/activerecord-5.2.5/lib/active_record/log_subscriber.rb:98
Favorite Load (0.1ms) SELECT "favorites".* FROM "favorites" WHERE "favorites"."user_id" = ? AND "favorites"."book_id" = ? LIMIT ? [["user_id", 13], ["book_id", 25], ["LIMIT", 1]]
↳ app/controllers/favorites_controller.rb:15
(0.1ms) begin transaction
↳ app/controllers/favorites_controller.rb:15
Favorite Destroy (0.6ms) DELETE FROM "favorites" WHERE "favorites"."id" = ? [["id", 201]]
↳ app/controllers/favorites_controller.rb:15
(3.4ms) commit transaction
↳ app/controllers/favorites_controller.rb:15
Book Load (0.1ms) SELECT "books".* FROM "books" WHERE "books"."id" = ? LIMIT ? [["id", 25], ["LIMIT", 1]]
↳ app/controllers/favorites_controller.rb:16
No template found for FavoritesController#destroy, rendering head :no_content
Completed 204 No Content in 61ms (ActiveRecord: 4.4ms)
該当のソースコード
class FavoritesController < ApplicationController def create Favorite.create(user_id: current_user.id, book_id: params[:book_id]) @book = Book.find(params[:book_id]) end def destroy Favorite.find_by(user_id: current_user.id, book_id: params[:book_id]).destroy @book = Book.find(params[:book_id]) end private def book_params @book = Book.find(params[:id]) end end
destroy.js.erb $('.favorite_buttons_' + <%= @book.id %>).html("<%= j(render "favorites/book-favorite", book: @book) %>");
<table class='table table-hover table-inverse'> <thead> <tr> <th></th> <th>Title</th> <th>Opinion</th> <th colspan="3"></th> </tr> </thead> <tbody> <% books.each do |book| %> <tr> <td> <%= link_to user_path(book.user) do %> <%= attachment_image_tag(book.user, :profile_image, :fill, 50, 50, fallback: "no-image-icon.jpg") %> <% end %> </td> <td><%= link_to book.title, book_path(book), class: "book_#{book.id}" %></td> <td><%= book.body %></td> <td class=<%= 'favorite_buttons_' + book.id.to_s %> > <%= render "favorites/book-favorite", book: book %> </td> <td> コメント数: <%= book.comments.count %> </td> </td> </td> <td> </td> </tr> <% end %> </tbody> </table>
試したこと
あなたの回答
tips
プレビュー