新手:越来越相互喜欢且仅当它们是相互有活动记录? [英] newbie : getting mutual likes and only if they are mutual with active record?

查看:252
本文介绍了新手:越来越相互喜欢且仅当它们是相互有活动记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这将是一个很好的方式来获得相互的喜欢?其中,2用户喜欢对方(如在好友列表),并只得到谁拥有相互匹配的那些用户?

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 )

我已经尝试了一些加入的,但不能真正得到它的工作,有没有建筑物AR功能获得上述结果?

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?

推荐答案

要添加到jexact的回答,这是你可以做到这一点使用AR一种方式:

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')

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

这篇关于新手:越来越相互喜欢且仅当它们是相互有活动记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆