auk63299
@auk63299 (ねりお ねり)

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

rails いいね機能 非同期処理ができない

Q&A

Closed

解決したいこと

いいね機能を非同期処理にできません。

ソースコード

index.html.erb
<div class="container mt-5">
  <div class="row">
    <div class="col-10 mx-auto">
      <table class="table table-hover">
        <thead class="thead-dark">
          <tr>
            <th scope="col">レシピ名</th>
            <th scope="col">投稿者</th>
            <th scope="col"> </th>
          </tr>
        </thead>
        <tbody>
          <% @recipes.each do |recipe| %>
            <tr>

              <td><%= link_to recipe.title, recipe_path(recipe) %></td>
              <td><%= recipe.user.name %></td>
              <div class='favorite-button' id="favorite-button_<%= recipe.id %>">
              <%= render 'favorite-button', recipe: recipe %>
              </div>
            </tr>
          <% end %>
        </tbody>
      </table>
    </div>
  </div>
</div>
_favorite-button.html.erb
<td>
     <% if recipe.liked_by?(current_user) %>
     <%= link_to 'いいねする', recipe_favorites_path(recipe), method: :delete, remote: true %>


     <%= recipe.favorites.count %>
     <% else %>
     <%= link_to 'いいね外す', recipe_favorites_path(recipe), method: :post, remote: true %>


     <%= recipe.favorites.count %>
     <% end %>
   </td>
favorites_controller.rb
class FavoritesController < ApplicationController
  def create
        @recipe = Recipe.find(params[:recipe_id])
        unless @recipe.liked_by?(current_user)
          favorite = current_user.favorites.new(recipe_id: @recipe.id)
          favorite.save

        end
    end

      def destroy
        @recipe = Recipe.find(params[:recipe_id])
        favorite = current_user.favorites.find_by(recipe_id: @recipe.id)
        favorite.destroy

      end
    end
create.js.erb
$("#favorite-button_<%= @recipe.id %>").html("<%= j(render 'recipes/favorite-button', recipe: @recipe ) %>");
destroy.js.erb
$("#favorite-button_<%= @recipe.id %>").html("<%= j(render 'recipes/favorite-button', recipe: @recipe ) %>");

自分で試したこと

これででるエラー

ターミナル
No template found for FavoritesController#create, rendering head :no_content

いいね押してもなにも変わらず、更新ボタン押すとちゃんと変わってくれるのですが、、
是非ご教授願います。

0

No Answers yet.

Your answer might help someone💌