问题
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