Last active
December 6, 2016 12:19
-
-
Save codebeige/37648c40739cdb8bbf21c15a284b71de to your computer and use it in GitHub Desktop.
Friendship queries
This file contains 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
class Friendship < ActiveRecord::Base | |
belongs_to :requester, class_name: 'User' | |
belongs_to :accepter, class_name: 'User' | |
scope :pending_and_confirmed, -> { unscope(where: :accepted_at) } | |
scope :confirmed, -> { unscope(where: :accepted_at).where.not(accepted_at: nil) } | |
scope :pending, -> { unscope(where: :accepted_at).where(accepted_at: nil) } | |
scope :by_user, ->(user) { where('requester_id = :user_id OR accepter_id = :user_id', user_id: user) } | |
default_scope { confirmed } | |
end |
This file contains 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
class User < ActiveRecord::Base | |
module FriendshipScopes | |
def pending | |
merge Friendship.pending | |
end | |
def confirmed | |
merge Friendship.confirmed | |
end | |
def pending_and_confirmed | |
merge Friendship.pending_and_confirmed | |
end | |
end | |
has_many :requested_friendships, ->{ extending FriendshipScopes }, class_name: 'Friendship', foreign_key: 'requester_id' | |
has_many :accepted_friendships, ->{ extending FriendshipScopes }, class_name: 'Friendship', foreign_key: 'accepter_id' | |
has_many :requested_friends, ->{ extending FriendshipScopes }, through: :requested_friendships, source: :accepter | |
has_many :accepted_friends, ->{ extending FriendshipScopes }, through: :accepted_friendships, source: :requester | |
def friendships | |
Friendship.by_user self | |
end | |
def friends(scope = nil) | |
unless scope | |
requested_friends + accepted_friends | |
else | |
requested_friends.send(scope) + accepted_friends.send(scope) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment