2011-08-27 55 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

相关问题