Created
June 29, 2021 18:45
-
-
Save izszzz/b50dd17a2d47579368b1cc998f9ceeb3 to your computer and use it in GitHub Desktop.
Rails5 following migration file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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