2014-04-19 4 views
1

User 모델은 다음과 같습니다레일 SQL 쿼리

has_many :relationships, foreign_key: "follower_id", dependent: :destroy 
has_many :followed_users, through: :relationships, source: :followed 

has_many :reverse_relationships, foreign_key: "followed_id", 
           class_name: "Relationship", 
           dependent: :destroy 
has_many :followers, through: :reverse_relationships, source: :follower 

는 내가 원하는 것은 주어진 사용자는 다음과에 의해 다시 다음에 한 사용자를 얻을 수있는 원시 SQL 쿼리입니다.

followed_user_ids = "SELECT followed_id FROM relationships 
          WHERE follower_id = #{user.id}" 

I 상호 친구를 반환하는 레일 방법을 가지고,하지만 난 SQL에 해당합니다 :

현재 나는 단지 내가 다음있어 사용자의 ID를 얻기로까지 왔

def mutual_friends 
    # interesect both arrays to find similar elements 
    self.followed_users & self.followers 
end 

답변

2

이런 식으로 뭔가가,

SELECT followed_id 
FROM relationships 
WHERE follower_id = #{user.id} AND followed_id IN (
    SELECT follower_id FROM relationships WHERE followed_id = #{user.id} 
) 
0

은 다음과 같이 사용하십시오 작동 나를 알고하도록해야 그것은 당신을 위해 작동합니다.

has_many :company_friendships, autosave: true 
has_many :company_friends, through: :company_friendships, autosave: true 
has_many :inverse_company_friendships, class_name: "CompanyFriendship", foreign_key: "company_friend_id", autosave: true 
has_many :inverse_company_friends, through: :inverse_company_friendships, source: :company, autosave: true 

def mutual_company_friends 
    Company.where(id: (company_friends | inverse_company_friends).map(&:id)) 
end