Skip to content

Instantly share code, notes, and snippets.

@izszzz
Created June 29, 2021 18:45
Show Gist options
  • Save izszzz/b50dd17a2d47579368b1cc998f9ceeb3 to your computer and use it in GitHub Desktop.
Save izszzz/b50dd17a2d47579368b1cc998f9ceeb3 to your computer and use it in GitHub Desktop.
Rails5 following migration file
class CreateUserRelationships < ActiveRecord::Migration[5.2]
def change
create_table :user_relationships do |t|
t.references :follower, foreign_key: { to_table: :users }
t.references :followed, foreign_key: { to_table: :users }
t.timestamps
t.index [:follower_id, :followed_id], unique: true
end
end
end
class User < ApplicationRecord
has_many :active_relationships, class_name: :UserRelationship,
foreign_key: :follower_id,
dependent: :destroy
has_many :passive_relationships, class_name: :UserRelationship,
foreign_key: :followed_id,
dependent: :destroy
has_many :following, through: :active_relationships, source: :followed
has_many :followers, through: :passive_relationships, source: :follower
end
class UserRelationship < ApplicationRecord
belongs_to :followed, class_name: :User
belongs_to :follower, class_name: :User
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment