How to calculate a record's ranking compared to others based on a single column in Rails? [closed]

僤鯓⒐⒋嵵緔 提交于 2019-12-25 07:25:11

问题


Assuming I have User model with a column called point.

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


回答1:


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

You would then call it as:

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.



来源:https://stackoverflow.com/questions/15697957/how-to-calculate-a-records-ranking-compared-to-others-based-on-a-single-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!