获取从ActiveRecord的秩ActiveRecord

2023-09-09 22:01:07 作者:蓝色天空

如果用户活动的分,我怎么能得到用户排名,假设标准定位:

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

我得到了不同的IM pression这将是数据库密集型的。我不是太担心这一点,但很明显的解决方案需要较少的处理能力都是赢家!

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!

如果让两个用户用点相同数量的同级别太复杂了,我是prepared接受用户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.

编辑:

我在一个单独的类实际上storin 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

这将返回3用户1和3。

This would return 3 for users 1 and 3.