Skip to content

Instantly share code, notes, and snippets.

@stevecass
Last active August 29, 2015 14:19
Show Gist options
  • Save stevecass/11ed44700dea44dcbb14 to your computer and use it in GitHub Desktop.
Save stevecass/11ed44700dea44dcbb14 to your computer and use it in GitHub Desktop.
Modelling followers
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :email
t.timestamps null: false
end
end
end
class CreateFollowings < ActiveRecord::Migration
def change
create_table :followings do |t|
t.integer :originator_id
t.integer :target_id
end
end
end
class User < ActiveRecord::Base
has_many :originated_followings, class_name: 'Following', foreign_key: :originator_id
has_many :received_followings, class_name: 'Following', foreign_key: :target_id
has_many :followed_people, through: :originated_followings, source: :target
has_many :followers, through: :received_followings, source: :originator
end
class Following < ActiveRecord::Base
belongs_to :originator, class_name: 'User', foreign_key: :originator_id
belongs_to :target, class_name: 'User', foreign_key: :target_id
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment