Вопрос

What would be a good way to get mutual likes ? where 2 users like each other ( as in a friendlist) and get only those users who have a mutual match?

user_id   | likes_id 
1           2                
2           1

Only get results where both of the users likes each other ( friendship )

I have tried some join's but can't really get it to work, is there a building AR feature to get the above results?

Это было полезно?

Решение

To add to jexact's answer this is one way you can do this using AR:

Like.joins('join likes l on likes.user_id=l.likes_id and l.user_id=likes.likes_id')

or

Like.select('l.*').joins('join likes l on likes.user_id=l.likes_id and l.user_id=likes.likes_id')

An alternative (slower? but imho looks cleaner) way is to do this in your User model (NOT tested, but should give you an idea):

class User < ActiveRecord::Base
  has_many :likes
  has_many :friends, :through => :likes

  has_many :liked_by, :foreign_key => 'likes_id', :class_name => 'Like'
  has_many :followers, :through => :liked_by, :source => :user

  def mutually_likes?(user)
    self.friends.include?(user) && self.followers.include?(user)
  end
end

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

I think this is what you're looking for: ruby on rails getting a 2-way friend relationship in active record?

Alternatively you can try this:

SELECT     a.user_id
FROM       likes AS a
INNER JOIN likes AS b
ON         a.user_id=b.likes_id
AND        a.likes_id=b.user_id

http://railscasts.com/episodes/163-self-referential-association

this way you can create relations between users, like I used this exemple to create relations between Media Companies and Companies hwo owns this Media (in my case), where a Media could be owned by a company A, and company A is owned by Company B and this is where you get the Self-Referential Association.

In your case is much simpler to implement this as you need users models.. for me it took more modifications to do.

I made it with

 @groups = Like.select('l.*').joins('join likes l on likes.user_id=l.likes and   l.user_id=likes.likes')

  unless @groups.empty?
    @groups.each do |group|
      friendship = Friendship.create(user_id: group.user_id, friend_id: group.likes)
    end
  end

The abstraction in model is nicer I look into that later on

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