LoginSignup
rrr013
@rrr013 (お腹 空いた)

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

Rails いいね機能 ajax コンソールエラー

解決したいこと

Ruby on Railsでいいね機能の非同期通信を実装しようとしています。
いいねを押しても非同期で押したことにされず、画面遷移をする事で、押したことになり、いいねの色が付きます。

解決方法を教えて下さい。

発生している問題・エラー

こちらいいねをしても、ハートが赤くならず、画面遷移やリロードすると
image.png
こちら↓のようにハートが赤くなります。
image.png

コンソールのエラーは、以下のになります。
スクリーンショット 2023-07-17 11.20.59.png

該当するソースコード

#favoriteコントローラー


class FavoritesController < ApplicationController
  before_action :authenticate_user!
  
  def create
    @book = Book.find(params[:book_id])
    favorite = current_user.favorites.new(book_id: @book.id)
    favorite.save
  end

  def destroy
    @book = Book.find(params[:book_id])
    favorite = current_user.favorites.find_by(book_id: @book.id)
    favorite.destroy
  end
  

end
#_favorite.html.erb


<% if book.favorited_by?(current_user) %>
    <%= link_to book_favorites_path(book), method: :delete, remote: true,data: {"turbolinks" => false}, class:'text-danger' do %>
      <i class="fas fa-heart"></i><%= "#{book.favorites.count}" %>
    <% end %>
<% else %>
    <%= link_to book_favorites_path(book), method: :post, remote: true,data: {"turbolinks" => false}, class:'text-primary' do %>
      <i class="fas fa-heart"></i><%= "#{book.favorites.count}" %>
    <% end %>
 <% end %>
#users/show.html.erb



<% @books.each do |book| %>
   <tr>

     <td>
       <%= link_to user_path(book.user) do %>
         <%= image_tag book.user.get_profile_image(80,80) %>
       <% end %>
     </td>

     <td><%= link_to book.title, book_path(book) %></td>
     <td><%= book.body %></td>
     
     <td>
       <div id="favorite_btn_<%= book.id %>">            
         <%= render 'favorites/favorite', book: book %>
       </div>
     </td>
     <td>
       <%= "コメント数:#{book.book_comments.count}" %>
     </td>
   </tr>
<% end %>
#create.js.erb

$('#favorite_btn_<%= @book.id %>').html("<%= j(render partial: 'favorites/favorite', locals: {book: @book}) %>");
#destroy.js.erb

$('#favorite_btn_<%= @book.id %>').html("<%= j(render partial: 'favorites/favorite', locals: {book: @book}) %>");

自分で試したこと

ここに問題・エラーに対して試したことを記載してください。

<% if book.favorited_by?(current_user) %>
    <%= link_to book_favorites_path(book), method: :delete, remote: true,data: {"turbolinks" => false}, class:'text-danger' do %>
      <i class="fas fa-heart"></i><%= "#{book.favorites.count}" %>
    <% end %>
<% else %>
    <%= link_to book_favorites_path(book), method: :post, remote: true,data: {"turbolinks" => false}, class:'text-primary' do %>
      <i class="fas fa-heart"></i><%= "#{book.favorites.count}" %>
    <% end %>
<% end %>

_favoriteの中にあるlink_toにdata: {"turbolinks" => false}を記載しました。

まだまだ初学者ですが、どうかよろしくお願いいたします。

0

No Answers yet.

Your answer might help someone💌