Search code examples
ruby-on-railsactiverecordmutual-friendship

rails activerecord, friend relation + inverse_friend relation how to get the mutual relation? code included


Trying to find the mutual relation, In a friends relations, Already have friends and inverse_friends. But how to combine them to get the mutual friends? Cannot seem to figure it out I tried several options and searched long time online, just don't see it

  has_many :friendships
  has_many :friends, :through => :friendships
  has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id"
  has_many :inverse_friends, :through => :inverse_friendships, :source => :user

how to get a

has_many :mutual_friends ?

Solution

  • I don't think you can define a mutual friends association. So, let's look at a mutual friends class method or scope.

    I assume that we want all our friends, for whom we are their friend.

    class User
      has_many :friendships
      has_many :friends, :through => :friendships
      has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id"
      has_many :inverse_friends, :through => :inverse_friendships, :source => :user
    
      def mutual_friends
        inverse_friends.joins(:friendships).where("friendships.user_id = users.id and friendships.friend_id = :self_id", :self_id => id).all
      end
    end
    

    To do it as an association, this would be what you are trying to do:

    has_many :mutual_friends,
             :through => :inverse_friendships,
             :source => :user,
             :conditions => ["friendships.user_id = users.id and friendships.friend_id = :self_id", :self_id => id]
    

    The problem is with the id method call in the has_many :mutual_friends association definition.