简体   繁体   中英

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 ?

Do you need two models to find mutual friends?

Couldn't you just do

@mutualfriends = @user1.friends & @user2.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.

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

Intersection of two relations

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM