Relationship.rb
class Relationship < ApplicationRecord
belongs_to :follower, class_name: "User"
belongs_to :followed, class_name: "User"
end
Relationshipモデル(中間モデル)には、
follower (フォローする人)
followed(フォローされる人)
が存在している。
user.rb
has_many :follower, class_name: "Relationship", foreign_key: "follower_id", dependent: :destroy
# フォロー取得。Relationshipモデルのfollower_idにuser_idを格納
has_many :followed, class_name: "Relationship", foreign_key: "followed_id", dependent: :destroy
# フォロワー取得。followed_idにuser_idを格納
上2行は、user主体で得る情報。
特定のアクションが起きた際、user_idが格納される場所をforeign_keyで指定することで、follower_id および followed_id の適切な方にuser_idを格納。
また、フォロー数等のときは、ユーザ情報の中身を必要としないので
<% current_user.follower.each do |user| %>
<%= user.count %>
<% end %>
のように、followerをとってよい(フォロー数取得)。
(フォロワー数を取得する場合は、followed)
user.rb
has_many :following_user, through: :follower, source: :followed
#following_userを命名。自分がフォローしているユーザ情報を取得。
has_many :follower_user, through: :followed, source: :follower
#自分をフォローしているユーザ情報を取得。
ユーザ情報を詳しく必要とする場合は、こちら(emailなど)。
<% current_user.following_user.each do |user| %>
<%= user.email %>
<% end %>
following_userで、followerテーブルを通じて、followedテーブルを参照。