はじめに
本記事は著者のプログラミング知識を整理し、「半年後の自分が見返しても理解できる記事」を目的に書かれています。また、著者と同じくプログラミング初学者の方を少しでも手助けれきると幸いです。
また、著者はプログラミングを学び始めてからまだ日が浅く、間違った情報、間違った認識を掲載している可能性があります。そういった箇所を発見された方は編集リスクエスト等でご連絡くださいませ。
ではいきます。
環境
ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin16]
Rails 5.1.4
※使用するgemは「acts as follower」
https://github.com/tcocca/acts_as_follower
※フォロー機能をもたせる下記Userモデルはgem 'devise'を用いて作成しました。
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
acts as followerを選んだ理由
・Qiitaにて既にgemを導入されている方が多数いらっしゃり情報量が豊富
・gemの導入後はall_followingやfollwersといったメソッドにより容易にフォロー関連のレコードを取得できる
導入手順
※アプリケーションの土台とUserモデルの作成は割愛させて頂きます。
gemを導入する
今回、私はRails5を使用しているためGemfileに下記を追記します。
source "https://rubygems.org"
git_source(:github) do |repo_name|
repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
"https://github.com/#{repo_name}.git"
end
...
gem "acts_as_follower", github: "tcocca/acts_as_follower", branch: "master"
...
Rails4以前だとGemfilへの記述が異なります。公式のGitHubを参照しましょう。
Gemfileへの記述が終わったらbundleを実行しましょう。
$ bundle update
$ bundle install
無事に完了したらジェネレータを走らせてFollowモデルを作成します。
$ rails generate acts_as_follower
下記のようなFollowモデルとマイグレーションファイルが自動生成されればOKです。
class Follow < ActiveRecord::Base
extend ActsAsFollower::FollowerLib
extend ActsAsFollower::FollowScopes
belongs_to :followable, polymorphic: true
belongs_to :follower, polymorphic: true
def block!
self.update_attribute(:blocked, true)
end
end
class ActsAsFollowerMigration < ActiveRecord::Migration[4.2]
def self.up
create_table :follows, force: true do |t|
t.references :followable, polymorphic: true, null: false
t.references :follower, polymorphic: true, null: false
t.boolean :blocked, default: false, null: false
t.timestamps
end
add_index :follows, ["follower_id", "follower_type"], name: "fk_follows"
add_index :follows, ["followable_id", "followable_type"], name: "fk_followables"
end
def self.down
drop_table :follows
end
end
マイグレーションの実行も忘れずに行いましょう。
$ rake db:migrate
Userモデルに「フォローする機能」を持たせる
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
acts_as_follower
end
こちらを追記することで他のUserモデルは他のモデルをフォローすることができるようになります。公式ではUserモデルがBookモデルをフォローするような実装になっていますが・・・同じモデル同士でフォローし合う場合でも実装方法は変わりません。
Userモデルに「フォローされる機能」を持たせる
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
acts_as_follower
acts_as_followable
end
これでOKです。Userモデルにはフォローしたりされたりする機能が追加されました。