我有一个rails应用程序,用户都有他们已经达到的分数。我想向用户显示其他用户的列表,这些用户的评分最接近他们自己。我希望这是用户得分+/-的顺序。我意识到我解释得很差,那么一个例子呢?
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.
按此顺序返回结果:
我该怎么做?
答案 0 :(得分: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)
答案 1 :(得分: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。