【Rails初心者学習記録】いいね機能を実装してみた
はじめに
Railsで「いいね機能」を実装した際の学習記録です。
ハートマークをクリックすることで、いいねしたり、いいねを消したりできる機能を実装しました。
1. いいね機能の設計
いいね機能は、ユーザーが投稿に対して1回だけ「いいね!」をつけたり外したりできる仕組みです。
-
favorites
テーブルを作成する -
favorites
テーブルを中間テーブルとして使い、User
とPost
の間に多対多のリレーションを作成する - ビューにいいねボタンを設置し、
create
とdestroy
のアクションで管理する
2. モデルとテーブルの作成
まず、いいねを管理する favorites
テーブルを作成します。
rails g model Favorite user_id:integer post_id:integer
rails db:migrate
3. アソシエーションの設定
app/models/user.rb
:
class User < ApplicationRecord
has_many :favorites, dependent: :destroy
end
app/models/post.rb
:
class Post < ApplicationRecord
has_many :favorites, dependent: :destroy
def favorited_by?(user)
favorites.where(user_id: user.id).exists?
end
end
app/models/favorite.rb
:
class Favorite < ApplicationRecord
belongs_to :user
belongs_to :post
end
4. コントローラーの実装
app/controllers/favorites_controller.rb
:
class FavoritesController < ApplicationController
def create
post = Post.find(params[:post_id])
favorite = current_user.favorites.new(post_id: post.id)
favorite.save
redirect_to post_path(post)
end
def destroy
post = Post.find(params[:post_id])
favorite = current_user.favorites.find_by(post_id: post.id)
favorite.destroy
redirect_to post_path(post)
end
end
5. ルーティングの設定
config/routes.rb
:
resources :posts do
resource :favorite, only: [:create, :destroy]
end
※いいねidの受け渡しが不要なので、resourceと単数にした。
6. ビューの実装
app/views/posts/_post.html.erb
:
<p class="caption"><%= @post.任意の項目 %>
<% if @post.favorited_by?(current_user) %>
<%= link_to post_favorites_path(@post), data: { turbo_method: :delete }, class: "favorite_btn" do %>
♥<%= @post.favorites.count %> いいね
<% end %>
<% else %>
<%= link_to post_favorites_path(@post), data: { turbo_method: :post }, class: "favorite_btn" do %>
♡<%= @post.favorites.count %> いいね
<% end %>
<% end %>
</p>
最後に
今後はAjaxを使って非同期処理を実装したいです!
最後まで読んでいただきありがとうございました!