ruby-on-rails – Rails 3 – 如何从带有订单的模型中获取行号

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 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)
=> [#<score player_name: "Keith Hughes",current_score: 9>,#<score player_name: "Diane Chapman",current_score: 8>,#<score player_name: "Helen Dixon",current_score: 4>,#<score player_name: "Donald Lynch",#<score player_name: "Shawn Snyder",current_score: 2>,#<score player_name: "Nancy Palmer",#<score player_name: "Janet Arnold",current_score: 1>,#<score player_name: "Sharon Torres",#<score player_name: "Keith Ortiz",current_score: 5>,#<score player_name: "Judith Day",current_score: 3>,#<score player_name: "Gregory Watson",current_score: 7>,#<score player_name: "Jeremy Welch",#<score player_name: "Sharon Oliver",#<score player_name: "Donald Lewis",#<score player_name: "Timothy Frazier",#<score player_name: "John Richards",#<score player_name: "Carolyn White",#<score player_name: "Ronald Smith",#<score player_name: "Emily Freeman",#<score player_name: "Gregory Wright",current_score: 2>]

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

解决方法

您可以计算具有更高current_score的记录数.您仍然必须按记录执行此操作(或在您的sql中执行子查询).
class score < ActiveRecord::Base

  def ranking
    score.count(:conditions => ['current_score > ?',self.current_score])
  end

end
原文链接:https://www.f2er.com/ruby/266487.html

猜你在找的Ruby相关文章