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

时光总嘲笑我的痴心妄想 提交于 2019-12-06 16:00:21

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
Rodrigo Zurek

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

Intersection of two relations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!