从 ActiveRecord 获取排名 [英] Getting a rank from ActiveRecord

查看:16
本文介绍了从 ActiveRecord 获取排名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果Users有积分,我如何获得用户排名,假设标准定位:

If Users have points, how can I get the user rank, assuming standard positioning:

require 'active_record'

class User < ActiveRecord::Base
  def rank
    # ???
  end
end

User.all
# => [<User id:1 points:100>, <User id:2 points:400>, <User id:3 points:100>, <User id:4 points:250>]

User.find_by_id(2).rank
# => 1
User.find_by_id(3).rank
# => 3
User.find_by_id(1).rank
# => 3

我有明显的印象,这将是数据库密集型的.我对此并不太担心,但显然需要较少处理能力的解决方案是赢家!

I get the distinct impression this will be database intensive. I'm not too worried about that, but obviously solutions which require less processing power are winners!

如果给两个分数相同的用户分配相同的排名太复杂了,我准备接受上面的用户 1 可能是 3 级,而用户 3 可能是 4 级.

If giving two users with the same number of points the same rank is too complex, I'm prepared to accept that user 1 above may be rank 3, and user 3 may be rank 4.

我实际上是在一个单独的班级中存储 Gmy 分数 - 因为每个事件都需要一定数量的积分.

I'm actually storin gmy scores in a seperate class - as each event warrants a certain amount of points.

class Event < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :events

  def points
    events.sum(:amount)
  end

  def rank
    # This seems a bit ham-handed
    Event.count_by_sql(['select count(*) from (select sum(amount) as points from events group by user_id) where points > ?',points]) + 1
  end
end

关于如何使这更简洁的任何想法?

Any ideas as to how to make this more succinct?

提前致谢

推荐答案

可以统计积分少的用户数,加一个.

You can count the number of users having less points, and add one.

def rank
  User.where("points > ?", points).count + 1
end

这将为用户 1 和 3 返回 3.

This would return 3 for users 1 and 3.

这篇关于从 ActiveRecord 获取排名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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