フォロー機能のモデルの構造の続きの投稿です。
上記の投稿内容では、フォローの関係を表すモデルの作成をしました。
では実際の、フォロー機能を実装していきましょう!
フォローとアンフォロー機能の実装
app/models/user.rb
class User < ApplicationRecord
has_many :microposts
has_many :relationships
has_many :followings, through: :relationships, source: :follow
has_many :reverses_of_relationship, class_name: 'Relationship', foreign_key: 'follow_id'
has_many :followers, through: :reverses_of_relationship, source: :user
def follow(other_user)
unless self == other_user
self.relationships.find_or_create_by(follow_id: other_user.id)
end
end
def unfollow(other_user)
relationship = self.relationships.find_by(follow_id: other_user.id)
relationship.destroy if relationship
end
def following?(other_user)
self.followings.include?(other_user)
end
end
なお、(other_user)は、他のユーザのページで、フォロー/アンフォローボタンを押したときに取得されると考えてください。
また、selfは自動で取得される自分自身を指します。
def follow(other_user)
unless self == other_user
self.relationships.find_or_create_by(follow_id: other_user.id)
end
end
では、自分自身(self)がフォロー対象(other_user)でない場合、other_userのidを返します。
find_or_create_by
は、find_or_create_by()の()で指定したものを探してみて無ければ作成しますよっていう記述です。
def unfollow(other_user)
relationship = self.relationships.find_by(follow_id: other_user.id)
relationship.destroy if relationship
end
は、relationshipに変数が入っていれば削除するという記述です。
def following?(other_user)
self.followings.include?(other_user)
end
ここでは、self.followings によりフォローしているUserを取得して、include?(other_user) でother_userが含まれていないかを確認しています。含まれている場合には、true を返し、含まれていない場合には、false を返します。
これで一応の処理は記述できました。