CarbazochromeT / drug_app

drug_app
0 stars 0 forks source link

Rails7でいいね機能をajax化したい #12

Closed CarbazochromeT closed 1 year ago

CarbazochromeT commented 1 year ago

https://qiita.com/iijima-naoya-45b/items/e35bc3f4c38a7f093700

show.html.erb

  <%= render 'like_button', drug: @drug  %>

_like_button.html.erb

<% if current_user.like?(drug) %>
  <%= render 'unlike', { drug: drug } %>
<% else %>
  <%= render 'like', { drug: drug } %>
<% end %>

_like.html.erb

<%= link_to likes_path(drug_id: drug.id),
            id: "js-like-button-for-drug-#{drug.id}",
             data: { turbo_method: "post" },
            remote: true do %>
  <%= icon 'far', 'star' %>
<% end %>

_unlike.html.erb

<%= link_to like_path(drug.id),
            id: "js-like-button-for-drug-#{drug.id}",
            data: { turbo_method: "delete" },
            remote: true do %>
  <%= icon 'fas', 'star' %>
<% end %>

likes_controller.rb

class LikesController < ApplicationController
  before_action :authenticate_user!   # ログイン中のユーザーのみに許可(未ログインなら、ログイン画面へ移動)

  def create
    @drug = Drug.find(params[:drug_id])
    current_user.like(@drug)

  def destroy
    @drug = current_user.likes.find(params[:id]).drug
    current_user.unlike(@drug)
  end
end
end

views/likes/create.turbo_stream.erb

<%= turbo_stream.replace "like-button-for-drug-#{@drug.id}" do %>
  <%= render 'drugs/unlike', drug: @drug %>
<% end %>

views/likes/destroy.turbo_stream.erb

<%= turbo_stream.replace "unlike-button-for-drug-#{@drug.id}" do %>
  <%= render 'drugs/like', drug: @drug %>
<% end %>