如何根据Rails中的单列计算记录与其他记录相比的排名? [英] How to calculate a record's ranking compared to others based on a single column in Rails?

查看:43
本文介绍了如何根据Rails中的单列计算记录与其他记录相比的排名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有 User 模型,其中有一列名为 point.

Assuming I have User model with a column called point.

与所有其他 User 行相比,我如何获得实例的排名.

How can I get an instance's ranking compared to all other User rows.

推荐答案

用户的排名可以被认为是其他用户的分数比他们多,再加上 1.正如 Mischa 在评论中指出的,一个合适的地方这将在用户模型本身中,如:

The user's rank can be thought of as the number other users with more points than them, plus 1. As Mischa pointed out in the comments, an appropriate place for this would be in the User model itself, as in:

def ranking
   User.where('point > ?', point).count + 1
end

然后您可以将其称为:

Rank: <%= @user.ranking %>

这有一个缺点,即在同一排名中对具有相同点数的用户进行排名.您必须为这种情况决定决胜局".

This has the downside of ranking users with the same number of points at the same rank. You'll have to decide on a "tiebreaker" for that case.

这篇关于如何根据Rails中的单列计算记录与其他记录相比的排名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆