Skip to content

Instantly share code, notes, and snippets.

@justinphelps
Created May 7, 2014 18:57
Show Gist options
  • Save justinphelps/1bd66d7777194f4776cd to your computer and use it in GitHub Desktop.
Save justinphelps/1bd66d7777194f4776cd to your computer and use it in GitHub Desktop.
Active Record following
# Study has_many, belongs_to methods (10 or so)
ActiveRecord::Migration.create_table :followings do |t|
t.belongs :follower
t.belong :stalked
end
ActiveRecord::Migrator.up "db/migrate"
class User < ActiveRecord::Base
# I follow people.
has_many :followings, foreign_key: "follower_id"
has_many: :stalked_users, through: :followings, source: :stalked
# People follow me.
has_many :opposite_followings, class_name: "Following", foreign_key: "stalked_id"
has_many :followers, through: :opposite_followings, source: :follower
def follow(user)
stalked_users << user
end
def stop_followin!
stalked_users.clear
end
def so_lonely?
end
end
class Following < ActiveRecord::Base
belongs_to :follower, class_name: "User"
belongs_to :stalked, class_name: "User"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment