Created
May 7, 2014 18:57
-
-
Save justinphelps/1bd66d7777194f4776cd to your computer and use it in GitHub Desktop.
Active Record following
This file contains hidden or 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
# 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