如果用户有积分,我如何获得用户排名,假设标准定位:
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.
编辑:
我实际上是在一个单独的课堂上分享gmy分数 – 因为每个事件都需要一定数量的分数.
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
关于如何使这更简洁的任何想法?
提前致谢