Railsチュートリアル14章 フォローとフォロワー

14章 フォローとフォロワーの関係がややこしいのでまとめる

 

ユーザーモデル内

class User < ApplicationRecord
  has_many :microposts, dependent: :destroy
  has_many :active_relationships,  class_name:  "Relationship",
                                   foreign_key: "follower_id",
                                   dependent:   :destroy
  has_many :passive_relationships, class_name:  "Relationship",
                                   foreign_key: "followed_id",
                                   dependent:   :destroy
has_many :following, through: :active_relationships, source: :followed
 active_relationshipsのforeignキーはfollower_idで逆じゃないのか?ってなったがこれで正しい。
これは片方(逆の関係であるもの)を固定することによって片方の情報を持ってきている。
図を見た方がわかりやすい(14.7)
active
followed | folower
1 2
2 1
3 1
4 1
foreignキーでfollewer_idを指定する(今回であれば1)によってフォローしているfollowedの情報を取ってくる。
has_many :followers, through: :passive_relationships, source: :follower
上と考え方一緒。逆の関係
図(14.9)
. . . end