2011-06-11 2 views
1

사용자의 '표시'페이지에서이를 표시하기 위해 사용자와 관련이있는 레코드 세트를 꺼내는 데 큰 어려움을 겪고 있습니다.컨트롤러 수 관계에서 자체 참조 찾기

는 여기에 아이디어 :

사용자 (current_user)는 두 개의 다른 사용자 (user_auser_b) 사이에 호환성 평가. 긍정적 또는 부정적으로 호환성을 평가할 수 있습니다. 두 명의 사용자가 "호환 가능"하다고 평가하면 user_a와 user_b 사이에 positive_connection이 생성되고 "호환되지 않음"으로 표시된 경우 negative_connection이 생성됩니다. 따라서 positive_connection, negative_connection 및 user에 대한 모델이 있습니다.

는 지금은 만 사용자를 표시해야 overall_positively_connected_to(@user) (즉, 어디 positive_connections_to(@user).count > negative_connections_to(@user).count)

내가에있어 곳입니다,하지만 난 더 이상 얻을 수 없습니다.

사용자 모델 :

def overall_positive_connected_to(user) 
     positive_connections_to(user).count > negative_connections_to(user).count 
    end 


    def positive_connections_to(user) 
     positive_connections.where("user_b_id = ?", user) 
    end  

    def negative_connections_to(user) 
     negative_connections.where("user_b_id = ?", user) 
    end 

컨트롤러

@user.user_bs.each do |user_b| 
    if user_b.overall_pos_connected_to(@user) 
    @compatibles = user_b 
    end 
end 

코드 I 컨트롤러가 분명히 잘못되었지만 어떻게해야합니까? 나는 레일스 (그리고 SQL)에 완전히 익숙하지 않았기 때문에, 순진한 것을했을지도 모른다.

도움이 될 것입니다.

답변

1

그래서 바로 당신이 3 개 모델

  • 사용자

    이 말하는 I 오전 (ID, 이름)
  • PositiveConnection (user_a_id, user_b_id)
  • NegativeConnection (user_a_id, user_b_id)

아니면 그런 종류의 것.

나는 방금 2 개 모델 을 할 생각 편의를 위해 나는 "FROM_USER"와 "to_user"

  • 사용자 (ID, 이름)
  • 연결 (값으로 관계 이름을 바꿀거야 : 정수, from_user_id, to_user_id)

값이 음수 인 경우 이면 -1이고 양수인 경우 +1입니다. (foreign_key와 : : : 당신이 정확한 같은 구문을 분류 할 필요가 참고 소스 및 물건) 이제

우리가 가질 수는 뭔가를 할

class User 

    has_many :connections, :foreign_key => "from_user_id" 
    has_many :connected_users, :through => :connections, :source => :to_user 

    def positive_connections 
    connections.where(:value => 1) 
    end 

    def negative_connections 
    ... 
    end 

end 

을 그러나 우리는 또한 지금 프레임 워크를 가지고 복잡한 SQL 쿼리를 생성 (다시 당신은 빈칸을 채울 필요가 ...하지만 같은)

class User 

    def positive_connected_users 
    connected_users.joins(:connections).group("from_user_id").having("SUM(connections.value) > 0") 
    end 

end 

이 매우 작업을 진행 것이 아니라 진짜 해결책

(순수한 SQL의 관점에서 생각하는 것이 더있을 수 있습니다)

SELECT users.* FROM users 
INNER JOIN connections ON to_user_id = users.id 
WHERE from_user_id = #{user.id} 
HAVING SUM(connections.value) > 0 
에 대한 의사 코드의 종류는
+0

Matthew에게 감사드립니다. 정확히 내가 찾고있는 것이 었습니다. 실제로 사용자가 두 명의 다른 사용자 간의 연결을 설정 한 다음 해당 연결에 투표하도록 내 모델을 완전히 변경하는 것이 결국 간단하다는 것을 알았습니다. 솔루션만큼이나 우아하지 않지만 제 목적을 위해 작동합니다. – jonic

+0

그래,이 계산을 현금화하기 위해 별도의 모델을 제시 할 것을 제안 했어야했다. 다른 어떤 큰 데이터 세트라도 느려질 것입니다. Mongo를 고려해 볼 수도 있습니다. Mongo를 사용하면 쉽게 할 수 있습니다. https://github.com/vinova/voteable_mongo에서 이와 비슷한 아이디어를 사용할 수 있기 때문에 확인하십시오. –