轨道3 - 如何从模型中的行号与订单 [英] Rails 3 - How to get the row number from a model with an order by
问题描述
我组建了一个小的应用程序,在它排行榜的概念。基本上,该模型仅仅是一个player_name和current_score
I am putting together a small app that has a leaderboard concept in it. Basically, the model is just a player_name and a current_score.
我想要做的就是一个特定玩家的排名,并给予新的分数进来的时候,它需要是动态的。很显然,我也只是做一个正常的找到order by子句,然后我将不得不通过每个记录的循环。不是很有效的时候,我可以10万个的行。
what I want to do is get the ranking of a specific player, and given that new scores are coming in all the time, it needs to be dynamic. Obviously I could just do a normal find with an order by clause and then I would have to loop through each record. Not very efficient when I could have 100,000's of rows.
这是我应该采取什么样的做法有什么建议?
Any suggestions on what approach I should be taking?
下面是表迁移:
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
编辑 举个例子,我有以下几点:
EDIT As an example, so I have the following:
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", current_score: 9>, #<Score player_name: "Shawn Snyder", current_score: 2>, #<Score player_name: "Nancy Palmer", current_score: 9>, #<Score player_name: "Janet Arnold", current_score: 1>, #<Score player_name: "Sharon Torres", current_score: 9>, #<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", current_score: 3>, #<Score player_name: "Sharon Oliver", current_score: 7>, #<Score player_name: "Donald Lewis", current_score: 7>, #<Score player_name: "Timothy Frazier", current_score: 7>, #<Score player_name: "John Richards", current_score: 1>, #<Score player_name: "Carolyn White", current_score: 4>, #<Score player_name: "Ronald Smith", current_score: 2>, #<Score player_name: "Emily Freeman", current_score: 9>, #<Score player_name: "Gregory Wright", current_score: 2>]
我怎样才能制定出唐纳德·刘易斯的排名?
How can I work out the ranking of "Donald Lewis" ?
推荐答案
您可以指望的具有更高current_score记录数。您仍然需要每条记录做(或做一个子查询您的SQL)。
You could count the number of records that have a higher current_score. You will still have to do it per record (or do a sub-query in your sql).
class Score < ActiveRecord::Base
def ranking
Score.count(:conditions => ['current_score > ?', self.current_score])
end
end
这篇关于轨道3 - 如何从模型中的行号与订单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!