Rails 3 – 如何从具有订单的模型中获取行号

我正在整理一个具有排行榜概念的小应用程序。 基本上,模型只是一个player_name和一个current_score。

我想要做的是获得特定玩家的排名,并且考虑到新的分数一直在进行,它需要是动态的。 显然,我可以使用order by子句进行正常查找,然后我必须循环遍历每条记录。 当我有100,000行时,效率不高。

我应该采取什么方法的任何建议?

以下是表的迁移:

class CreateScores < ActiveRecord::Migration def self.up create_table :scores do |t| t.string :player_name t.integer :current_score t.timestamps end end def self.down drop_table :scores end end 

编辑作为一个例子,所以我有以下内容:

 Score.select('player_name, current_score').limit(20) => [#, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #] 

我如何计算出“唐纳德刘易斯”的排名?

您可以计算具有更高current_score的记录数。 您仍然必须按记录执行(或在您的sql中执行子查询)。

 class Score < ActiveRecord::Base def ranking Score.count(:conditions => ['current_score > ?', self.current_score]) end end 
 Score.find(:select => "player_name,max(current_score) as high_score",:group_by => "player_name",:order => "max(current_score) DESC")