Skip to content

Instantly share code, notes, and snippets.

@ltw
Created October 26, 2015 18:32
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 ltw/4125dafe94f6b76ff6fa to your computer and use it in GitHub Desktop.
Save ltw/4125dafe94f6b76ff6fa to your computer and use it in GitHub Desktop.
A brief model of Friendship in ActiveRecord
# users
# id | name | email
class User < ActiveRecord::Base
has_many :friendships
has_many :friends, through: :friendships
def friends
User.join(:friendships).where('friendships.user_id = ? OR friendships.friend_id = ?', self.id, self.id)
end
end
# friendships
# id | user_id | friend_id
class Friendship < ActiveRecord::Base
belongs_to :user
belongs_to :friend, class_name: 'User'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment