Closed CarbazochromeT closed 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 %>
https://qiita.com/iijima-naoya-45b/items/e35bc3f4c38a7f093700
show.html.erb
_like_button.html.erb
_like.html.erb
_unlike.html.erb
likes_controller.rb
views/likes/create.turbo_stream.erb
views/likes/destroy.turbo_stream.erb