Sign in through GitHub

Please read for an updated status on RailsCasts:

Learn more or hide this

weiserma's Profile

GitHub User: weiserma

Comments by

Avatar

I came up with this solution to bidirectional with methods for:
* mutual - relationship in both directions
* pending - relationship only forward
* requesting - relationship only backward

ruby friend.rb
class Friend < ActiveRecord::Base
  belongs_to :profile
  belongs_to :friend, :class_name => 'Profile'
end
ruby profile.rb
class Profile < ActiveRecord::Base
    has_many  :friends
    has_many  :friend_profiles, :through => :friends, source: :friend
    has_many  :friended_by, class_name: "Friend"  , :foreign_key => "friend_id"
    has_many  :friended_by_profiles, :through => :friended_by, source: :profile
   
    
    def mutual_friends
      friended_by.where('profile_id in (?)', friend_profile_ids)
    end
    
    def mutual_friend_profiles
      Profile.where('id in (?)', mutual_friends.pluck(:profile_id))
    end
    
    def requesting_friends
      friended_by.where('profile_id not in (?)', friend_profile_ids)
    end
    
    def requesting_friend_profiles
      Profile.where('id in (?)', requesting_friends.pluck(:profile_id))
    end
    
    def pending_friends
      friends.where('friend_id not in (?)', friended_by_profile_ids)
    end
    
    def pending_friend_profiles
      Profile.where('id in (?)', pending_friends.pluck(:friend_id))
    end
end

Any suggestions for improvement?