LoginSignup
25
38

More than 5 years have passed since last update.

Railsでフォロー/フォロワー機能を実装する

Posted at

はじめに

RailsでTwitterのようなフォロー/フォロワーの機能を実装する方法を紹介します。

環境

Ruby 2.3.1
Rails 5.0.0.1
Mac OS X Yosemite 10.10.5

扱うモデル

今回はUserというモデルに対して、フォロー/フォロワーの関係を実装します。

user.rb
class User < ApplicationRecord
end

Gem

acts_as_followerというGemを使用します。
https://github.com/tcocca/acts_as_follower

Rails5

Gemfile
gem "acts_as_follower", github: "tcocca/acts_as_follower"

※Rails5だと現時点のリリースではエラーが起きるため、githubから取得するようにしています。

Rails4

Gemfile
gem 'acts_as_follower'

※Rails3以前だと方法が異なりますので、公式を参照して下さい。

bundle install

bundle install

Followモデルとテーブルを作成

rails generate acts_as_follower

これにより、以下のファイルが生成されます

create  db/migrate/{日時}_acts_as_follower_migration.rb
create  app/models/follow.rb

マイグレーションを実行します。

rails db:migrate

Userモデルへフォロー/フォロワーの関係を実装

以下をUserモデルへ追記します。

user.rb
class User < ApplicationRecord
  acts_as_followable # フォロワー機能
  acts_as_follower   # フォロー機能
end

これでモデルへの実装は完了です。
早速、実行していきましょう。

フォロー/フォロワー機能を使用する

フォローする

taro = User.find(1)
jiro = User.find(2)
taro.follow(jiro) # taroがjiroをfollowする

フォローしているユーザを取得する

taro.all_following # フォローしているUserの配列が返る

フォローされているユーザ(フォロワー)を取得する

jiro.followers # フォローされているUserの配列が返る

フォローしているかを確認する

taro.following? jiro # true

フォローされているかを確認する

taro.followed_by? jiro # false

フォロー数を取得する

taro.follow_count # 1

フォロワー数を取得する

jiro.followers_count # 1

フォローを取り消す

taro.stop_following(jiro) # taroからjiroへのフォローを削除する

おわりに

同じモデル同士でない場合のフォロー/フォロワー(例えば、User⇔Bookなど)も簡単に実装することができますので、
興味を持たれた方は、公式のREADMEを読むとより便利そうです。
https://github.com/tcocca/acts_as_follower

25
38
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
25
38