Created
October 26, 2015 18:32
-
-
Save ltw/4125dafe94f6b76ff6fa to your computer and use it in GitHub Desktop.
A brief model of Friendship in ActiveRecord
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
# 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