2014-03-25 5 views
1

자체의 많은이 있습니다,하지만 난레일은 광산과 같은 몇 가지 질문이 있습니다

rails many to many self join

Many-to-many relationship with the same model in rails?

내 상황이 많은 친구와 사용자 같은 것입니다 찾고 있어요 확실히 무엇인지.

class User 
    has_many connections 
    has_many friends, through: connections, class_name: 'User' 
end 

class Connection 
    belongs to :user 
    belongs to :friend, class_name: 'User' 
end 

이 나에게 아주 가까이 도착, 내가 할 수있는 :

first = User.create 
second = User.create 

first.friends << second 
first.friends # => [ second ] 

나는 문제는 "친구"쿼리가 있다는 두 가지

first.friends << second 
second.friends # => [ first ] 

을 갈 수있는 연결을 싶습니다 User_id에 대한 연결을 찾고, 모든 friend_ids를 찾는다. user_id가 "second"인 연결이 없기 때문에 "second"는 연결이 없습니다.

두 가지 해결책을 생각하고 있습니다. 1) 첫 x 째 연결이 작성 될 때 user_id = "second"로 다른 연결을 작성하십시오. 2) "친구"방법을 재정 의하여 알아낼 SQL 쿼리를 생성하십시오.

이것에 대한 의견이 있으십니까? 감사.

+0

미안 전체 응답 시간이 없어하지만 당신은이를 찾을 수 있습니다 귀하의 상황에 도움이 될 수 있습니다. http://railscasts.com/episodes/163-self-referential-association – Harry

답변

0

당신이에 의해이

first.friends << second 
second.friends << first 

처럼 그것을 할 수 있습니다 당신은 둘 다있을 것이다 또는 당신은 두 번째 관계를 만들 수 있습니다 rayn style

관련 문제