LoginSignup
2
1

More than 3 years have passed since last update.

[Ruby on rails] いいね機能の実装

Posted at

はじめに

投稿アプリで他のユーザーがいいねを出来るようにいいね機能を実装。
usersテーブルとpostsテーブルとlikesテーブルがあるものとします。

アソシエーション

まずは、各テーブルの関係性を考え、アソシエーションを定義します。
ユーザー(1):いいね(多)
投稿(1):いいね(多)
1人1投稿に1回のいいねまでにしたいのでバリデーションもかけます。

like.rb
class Like < ApplicationRecord
  belongs_to :user
  belongs_to :post

  validates_uniqueness_of :post_id, scope: :user_id

end

投稿が削除されたされた場合いいねも削除。

post.rb
has_many :likes, dependent: :destroy
user.rb
has_many :likes, dependent: :destroy

def already_liked?(post)
  self.likes.exists?(post_id: post.id)
end

コントローラー実装

likes_controller.rb
class LikesController < ApplicationController

  def create
    @like = current_user.likes.create(post_id: params[:post_id])
    redirect_back(fallback_location: root_path)
  end

  def destroy
    @post = Post.find(params[:post_id])
    @like = current_user.likes.find_by(post_id: @post.id)
    @like.destroy
    redirect_back(fallback_location: root_path)
  end

end

ルーティングの設定

routes.rb
resources :posts do
  resource :likes, only: [:create, :destroy]
end

post_likes
DELETE /posts/:post_id/likes(.:format) likes#destroy
POST /posts/:post_id/likes(.:format) likes#create

viewの実装

~.html.erb
<% if current_user.already_liked?(post) %>
  <%= link_to post_likes_path(post), method: :delete do %>
    <i class="fas fa-heart"></i>
  <% end %>
<% else %>
  <%= link_to post_likes_path(post), method: :post do %>
    <i class="far fa-heart"></i>
  <% end %>
<% end %>
<%= post.likes.count %>    //いいねの数を表示

すでにcurrent_userがいいねしているか?
trueであればいいねを解除して、falseであればいいねをする。

最後に

いいねの実装方法は他にも非同期での実装などもあります。
まだまだ勉強中ですが、色々な技術を勉強し出来ることを増やしていきたいと思います。
最後まで読んでいただきありがとうございます:grin:

2
1
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
2
1