如果 User
有积分,假设标准定位,我如何获得用户排名:
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
我得到明显的印象,这将是数据库密集型的。我不太担心这一点,但显然需要较少处理能力的解决方案是赢家!
如果给两个具有相同分数的用户相同的排名太复杂,我准备接受上面的用户 1 可能是排名 3,而用户 3 可能是排名 4。
编辑:
我实际上将我的分数存储在一个单独的类(class)中 - 因为每个事件都会保证一定数量的分数。
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
关于如何使它更简洁的任何想法?
提前致谢
最佳答案
你可以数一数积分少的用户数,然后加一。
def rank
User.where("points > ?", points).count + 1
end
这将为用户 1 和 3 返回 3。
关于sql - 从 ActiveRecord 获取排名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7103767/