newbie : getting mutual likes and only if they are mutual with active record?

岁酱吖の 提交于 2019-12-25 04:59:31

问题


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?


回答1:


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



回答2:


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



回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/11294147/newbie-getting-mutual-likes-and-only-if-they-are-mutual-with-active-record

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