1
0

More than 1 year has passed since last update.

いいね!機能の実装方法

Posted at

いいね機能の実装方法をこちらに記載致します。

まず最初にmoelのlike.rbを作成し、その後、ユーザーモデルと投稿にあたるモデルにhas_manyを使って関連づけます。

class Like < ApplicationRecord
  belongs_to :user
  belongs_to :shop
end
class User < ApplicationRecord
  has_many :likes
end
class Shop < ApplicationRecord
  has_many :likes
end

続いていいね!ボタンを表示したいファイルでの書き方を説明します。
ボタンを押すことにより、見た目が変化するため、if文を設置する必要があります。

<% if current_user.likes.exists?(shop_id: shop.id) %>
  <%= link_to delete_like_path(shop), method: :delete, class: "like-btn" do %>
    <i class="fas fa-heart liked"></i>
  <% end %>
<% else %>
  <%= link_to like_path(shop), method: :post, class: "like-btn" do %>
    <i class="far fa-heart"></i>
  <% end %>
<% end %>

以下のコードをroutes.rb内に記載します。

resources :likes, only: [:create, :destroy]

そして、次にcontrollerファイルを作成し、いいね!をした時としてない時のアクションを作成します。


class LikesController < ApplicationController
  before_action :authenticate_user! # ユーザーがログインしていることを確認するフィルター

  def create
    @shop = Shop.find(params[:id])
    current_user.likes.create(shop: @shop)
    redirect_to shop_path(@shop), notice: 'いいね!しました。'
  end

  def destroy
    @shop = Shop.find(params[:id])
    current_user.likes.find_by(shop: @shop).destroy
    redirect_to shop_path(@shop), notice: 'いいね!を解除しました。'
  end
end

また、ボタンに動きを付けるためにapp/assets/javascriptsにshop.jsを追加する必要があります。
コード内容は以下のようになっています。

<% @shops.each do |shop| %>
  <div class="shop-tile">
    <!-- Shopの情報表示部分 -->

    <!-- いいねボタン -->
    <div class="like-btn">
      <% if current_user.likes.exists?(shop_id: shop.id) %>
        <%= link_to delete_like_path(shop), method: :delete, class: "unlike-link" do %>
          <i class="fas fa-heart liked"></i> いいね解除
        <% end %>
      <% else %>
        <%= link_to create_like_path(shop), method: :post, class: "like-link" do %>
          <i class="far fa-heart"></i> いいね
        <% end %>
      <% end %>
    </div>
  </div>
<% end %>

これらのコードを書くことにより、いいね!ボタンの機能を実装することが出来ます。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0