Skip to content

Instantly share code, notes, and snippets.

@EdgarOrtegaRamirez
Created May 23, 2015 18:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EdgarOrtegaRamirez/60ce85399a12e87fa637 to your computer and use it in GitHub Desktop.
Save EdgarOrtegaRamirez/60ce85399a12e87fa637 to your computer and use it in GitHub Desktop.
Users - Followers - Following
class CreateRelations < ActiveRecord::Migration
def change
create_table :relations do |t|
t.references :user, index: true, foreign_key: true
t.integer :friend_id, index: true
t.timestamps null: false
end
end
end
class Relation < ActiveRecord::Base
belongs_to :user
belongs_to :friend, class_name: "User"
validates_uniqueness_of :user_id, scope: :friend_id
end
class User < ActiveRecord::Base
has_many :follower_relations, class_name: "Relation", foreign_key: :friend_id
has_many :following_relations, class_name: "Relation", foreign_key: :user_id
has_many :followers, through: :follower_relations, source: :user
has_many :followings, through: :following_relations, source: :friend
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment