フォロー・フォロワー機能のモデル

テーブル設計

$ rails g model relationship follower_id:integer followed_id:integer

マイグレーションファイルを修正

class CreateRelationships < ActiveRecord::Migration[5.2]
  def change
    create_table :relationships do |t|
      t.integer :follower_id
      t.integer :followed_id

      t.timestamps
    end
    add_index :relationships, :follower_id
    add_index :relationships, :followed_id
    add_index :relationships, [:follower_id, :followed_id], unique: true
  end
end

follower_idfollowed_idの組み合わせをユニーク制約

$ rails db:migrate

モデルの設定

(app/models/user.rb)

 has_many :active_relationships, 
            foreign_key: 'follower_id', 
            class_name: 'Relationship', 
            dependent: :destroy
  has_many :passive_relationships, 
            foreign_key: 'followed_id', 
            class_name: 'Relationship', 
            dependent: :destroy
  has_many :following, 
            through: :active_relationships, 
            source: :followed
  has_many :followers, 
            through: :passive_relationships, 
            source: :follower

(app/models/relationships.rb)

class Relationship < ApplicationRecord
  belongs_to :followed, class_name: "User"
  belongs_to :follower, class_name: "User"
end