LoginSignup
0
1

More than 3 years have passed since last update.

【rails】フォロー機能2~機能の実装

Posted at

フォロー機能のモデルの構造の続きの投稿です。
上記の投稿内容では、フォローの関係を表すモデルの作成をしました。
では実際の、フォロー機能を実装していきましょう!

フォローとアンフォロー機能の実装

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 を返します。

これで一応の処理は記述できました。

0
1
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
0
1