LoginSignup
13
19

More than 3 years have passed since last update.

railsでのマッチング機能(フォロー機能)の実装

Last updated at Posted at 2019-08-03

マッチング機能(フォロー機能)の実装

Railsでマッチング機能の実装をしたので、コードの記録と解説をしていきます。

マッチング機能とは、要は、フォロー機能を言い換えただけなので、機能自体はフォロー機能と同じです。

今回使うGemは、”acts_as_folloer"。

このGemを導入することで簡単に機能の実装をすることができます。

全て下記の、githubに記載されていますので、詳しく知りたいという方は下記をご参考にしてください。
https://github.com/tcocca/acts_as_follower

Gemfile

gemfile.
gem "acts_as_follower", github: "tcocca/acts_as_follower"

Gemを最下部に追加。
railsのバージジョンが4.0以下の時に、 github下の記述はいりません。

Userモデル

user.rb
class User < ApplicationRecord
  acts_as_followable 
  acts_as_follower
end

Userモデルでフォロー・フォロワー関係をあらわすアソシエーションを組む。

ルーティング

routes.rb
  put 'users/follow/:user_id',to: 'users#follow'
  put 'users/unfollow/:user_id',to: 'users#unfollow'
  get 'users/follow_list/:user_id',to: 'users#follow_list'
  get 'users/follower_list/:user_id',to:'users#follower_list'

ユーザーのフォローする、フォローを外す、フォローリストを表示する、フォロワーリストを表示するといったルーティングを組む。

コントローラーの記載

users_controller.rb
  def follow
    @user = User.find(params[:user_id])
    current_user.follow(@user)
    redirect_to user_path(@user)
  end

  def unfollow
      @user = User.find(params[:user_id])
      current_user.stop_following(@user)
      redirect_to user_path(@user)
  end


  def follow_list
    @user = User.find(params[:user_id])
  end

  def follower_list
    @user = User.find(params[:user_id])
  end

インスタンス変数を使ってレコードからそれぞれの値を取得し、必要に応じてリダイレクト設定を行う。

followingやstop_followingなどのAPIを使うことで、フォローをしたり外したりといった動作ができるようになる。

ビューの記載(一部)

user/shows.html.erb

 <%if current_user.id==@user.id%>
  <%= @user.follow_count %>
   <%= link_to "人気になる", {controller: :users,action: :follow_list,user_id: @user.id}, method: :get %>
  <%= @user.followers_count %>
   <%= link_to "人あなたを気になる", {controller: :users,action: :follower_list,user_id: @user.id}, method: :get%>
<%end%>

現在ログインしているユーザーにフォロー・フォロワーが何人いるかcountを使う。
そのリンクが押されたlink_toには、コントローラーで指定したusersコントローラーのfollow_list、ビューに送るパラメーターを設定する。

_follow.html.erb
<%unless current_user.id==@user.id%>
<div id="follow_form">
  <% if current_user.following? @user %>
    <%= link_to "気になる削除", {controller: :users,action: :unfollow,user_id: @user.id}, method: :put, class:"btn btn-red50_rsd"%>
  <% else %>
    <%= link_to "気になる", {controller: :users,action: :follow,user_id: @user.id}, method: :put ,class:"btn btn-red50_rsd" %>
  <% end %>
</div>
<% end %>

現在ログインしているユーザー以外のページでは、フォローフォームをrenderで呼び出し、上記と同じくコントローラ、アクション、パラメーターの指定を行う。

まとめ

このような流れで簡単にフォロー・フォロワー関係を作ることができます。

13
19
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
13
19