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