4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Favorite】Rails いいね機能 実装

Last updated at Posted at 2020-04-29

画面収録 2020-04-30 0.34.38.mov.gif

#【ゴール】
ユーザーに投稿に対していいね機能を実装する
いいねを押すとハートが赤くなる

参考:https://qiita.com/nojinoji/items/2c66499848d882c31ffa

#【メリット】
UI、UXの向上
アソシエーションの理解度向上

#【開発環境】
■ Mac OS catalina
■ Ruby on Rails (5.2.4.2)
■ Virtual Box:6.1
■ Vagrant: 2.2.7

#【実装】 "user" "post"機能実装は割愛

  1. favorite model作成
mac.terminal
$ rails g model Favorite
  1. アソシエーション 追記

※ user : favorite = 1 : 多 
※ post : favorite = 1 : 多

models/post.rb
has_many :favorites
def favorited_by?(user)
    favorites.where(user_id: user.id).exists?
end
models/user.rb
has_many :favorites
models/favorite.rb
belongs_to :user
belongs_to :post

route 追記
※ "favorite" は "post" に関連しているのでルートをネスト(親子)させる

config/routes.rb
resources :posts do
    resources :favorites , only: [:create , :destroy]
end

favorite controller作成
※ "create" , "destroy"も一緒に作成

mac.terminal
$ rails g controller Favorites create destroy

favorite controller記述
① , ②で user_id post_id をparameterに渡す

favorites_controller.rb
class FavoritesController < ApplicationController
  def create
  	@post = Post.find(params[:post_id]) ①
    favorite = @post.favorites.new(user_id: current_user.id) ②
    favorite.save
    flash[:success] = "Liked post"
  	redirect_to request.referer
  end

  def destroy
  	@post = Post.find(params[:post_id]) ①
    favorite = current_user.favorites.find_by(post_id: @post.id) ②
    favorite.destroy
  	redirect_to request.referer
  end
end

view記述
※ modelで記述 ”@post.favorited_by?” を使用

post/show.html/erb
<% if @post.favorited_by?(current_user) %>
   <%= link_to post_favorite_path(@post), method: :DELETE do %>
   <i class="fa fa-heart" aria-hidden="true" style="color: red;"></i>
   <%= @post.favorites.count %>like
   <% end %>
<% else %>
  <%= link_to post_favorites_path(@post) , method: :POST do %>
  <i class="fa fa-heart-o" aria-hidden="true"></i>
  <%= @post.favorites.count %>like
  <% end %>
<% end %>

以上

4
5
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
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?