Skip to content

Instantly share code, notes, and snippets.

@zhuochun
Created December 22, 2013 11:14
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 zhuochun/8081009 to your computer and use it in GitHub Desktop.
Save zhuochun/8081009 to your computer and use it in GitHub Desktop.
class User < ActiveRecord::Base
#let's just make it simple and only add one column for this model called 'username'
attr_accessible :username
#use "follower_id" as the foreign key since by default it will use "user_id" which does
#not exist inside the "relationships" table
has_many :relationships, foreign_key: :follower_id
#find all user with the ID matching the "followed_user_ids" of the result. If I did not
#include "source: :followed_user", it will look for the column "following_id" which is wrong
has_many :followings, through: :relationships, source: :followed_user
#here we are just reversing the relationship. Instead of using "follower_id", we now use
#"followed_user_id"
has_many :inverse_relationships, class_name:"Relationship", foreign_key: :followed_user_id
#this line will look for the "follower_id" based on the result of the "inverse_relationships".
#no "source" option is required since we have used the "followers" in the association thus
#it looks for a "follower_id" on the "relationships" table which it does
has_many :followers, through: :inverse_relationships
end
class Relationship < ActiveRecord::Base
#Here, class_name just means that it's a User model.
belongs_to :follower, class_name: "User"
belongs_to :followed_user, class_name: "User"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment