2011-08-27 4 views
1

사용자가 모두 달성 한 점수를 가진 레일 앱이 있습니다. 나는 가장 가까운 점수를 가진 다른 사용자의 목록을 사용자에게 보여주고 싶습니다. 나는 이것이 사용자 점수에서 +/-의 순서로되기를 원합니다. 나는 이것을 잘 설명하지 못한다는 것을 깨닫는다. 예를 들어 보자. 나는이 쿼리를 수행 할 때Rails 3의 정수 근접성을 기반으로 한 쿼리

current_user.score = 825 

user1.score = 827 
user2.score = 818 
user3.score = 824 
user4.score = 887 

그래서 :

  • 사용자 3
  • 사용자 1
  • 사용자 2
  • USER4
  • ,536 :

    User.where("score NEAR ?", current_user.score).order("proximity ASC") # I'm just making this up. 
    

    그것은이 순서로 결과를 반환

어떻게해야합니까?

답변

1
User.find(:all, :order => "ABS(score - #{current_user.score}) DESC") 

또는, 당신은 값을 유지하려면 : 당신이 current_user.score을 소독해야 물론

User.find(:all, 
      :select => "*, ABS(score - #{current_user.score}) as diff", 
      :order => 'diff DESC') 

.

3
User.where(:score => (current_user.score - offset)..(current_user.score + offset)) 

또 다른 방법 :

# 5 higher scores higher than the user's 
User.where("score >= ? AND id != ?", current_user.score, current_user.id).order("score ASC").limit(5) 
# 5 scores lower than the user's 
User.where("score <= ? AND id != ?", current_user.score, current_user.id).order("score DESC").limit(5) 
+0

첫 번째 방법에서 오프셋은 어디서 발생합니까? 두 번째 방법에서는 점수가 현재 사용자보다 높은 사용자 만 반환합니다. – goddamnyouryan

+0

오프셋은 프로그램의 다른 변수입니다. 두 번째 질문에 대한 나의 대답은 편집 된 대답을 참조하십시오. – dteoh