2012-03-23 2 views
0

私はプレイヤーのランキングを幅広く提供し、コントローラ/ビューの構築このモデルを使用しています(例:「トップ10リーダーボードを」。):私のコントローラでRails 3 - 属性の数学を使ってARクエリ結果を並べ替えるにはどうすればいいですか?

class Player < ActiveRecord::Base 
    attr_accessible :name, :games_played, :games_lost, :games_won, games_exited, 
        :total_kills, :total_deaths, :total_points, :total_coins 
end 

私が合格するためにいくつかの明白なクエリ結果を持っています

@top_winners = Player.order("games_won DESC").limit(10) 
@top_assassins = Player.order("total_kills DESC").limit(10) 

ここで、計算であるソートされたランキングを追加する必要があります。例:

@most_greedy would be sorted on:  :total_coins/:games_played 
@most_lethal would be sorted on:  :total_kills/:games_played 
@most_vanquished would be sorted on: :total_deaths/(:games_lost + :games_exited) 

私のアプローチは、アレイ内のすべてのプレーヤーを取得し、Rubyのarray.sort {| a,b | block } → new_arrayオプションを使用することです。残念ながら、私のわずかなAR理解とRubyのスキルが私を失敗している

undefined local variable or method `x' for #<PlayersController:0x007fb7dac59d08> 

:エラーが発生し

rich_players = Player.order("total_coins DESC").limit(30) # only consider top 30 richest 
@most_greedy = rich_players.sort {|total_coins, games_played| x/y }.slice(0, 9) 

@most_greedyの場合、私はこれを試してみました。このアプローチはどのように機能させることができますか?このタイプの問題には別のアプローチがありますか?私はこのようなARのクエリガイドで何も見ていない。

答えて

2

sortはアクティブなレコードではありません。これは普通の古いルビーであり、2つのパラメータを持つブロックを使用して、Playerオブジェクトになる両方のオブジェクトを比較します。

sort_byを使用して
@most_greedy = rich_players.sort {|x, y| 
    (x.total_coins/x.games_played) <=> (y.total_coins/y.games_played) 
}.slice(0, 9) 

あるいはさらに良い、:

@most_greedy = rich_players.sort_by {|x| 
    x.total_coins/x.games_played 
}.slice(0, 9) 

あなたはすなわち、異なる結果をもたらす可能性がある(calulateするためにデータベースを使用する場合は、より良いスコアを持っているより少ないweathlyプレイヤーを見つけることができますあなたがこれを試してみるかもしれない...(未テスト)

@most_greedy = Player.select('*, total_coins/games_played as greediness').order('greediness DESC').limit(10) 
+0

私はあなたの答えの 'sort_by'バージョンを試してみました。 'sort_by'は昇順に並べ替えるので、.sliceの後に.reverseを追加して、「降順で上位10位」の結果を得なければなりませんでした。ありがとう! –

+0

私もあなたの答えで最後の/ DBオプションを試しました:Player.select(...それはまた働いた。ありがとうもう一度。 –

関連する問題