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

StackOverflow https://stackoverflow.com/questions/12468084

Вопрос

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 ?
Это было полезно?

Решение

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.

Другие советы

Do you need two models to find mutual friends?

Couldn't you just do

@mutualfriends = @user1.friends & @user2.friends

try the intersection of two querys here is a thread about that

Intersection of two relations

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top