2011-08-27 28 views
1

我有一個Rails應用程序,用戶都有他們已經實現的分數。我想向用戶顯示其他用戶的列表,他們與自己的評分最接近。我希望這是從用戶分數的+/-的順序。我意識到我解釋得很糟糕,那麼一個例子呢?基於Rails 3中一個整數的接近度來查詢

current_user.score = 825 

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

所以,當我做這個查詢:

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

它返回順序結果:

  • 用戶3
  • USER1
  • user2的
  • USER4

我該如何去做這件事?

回答

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

,或者,如果你想保留的值:

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

當然你應該消毒current_user.score。

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