私はプレイヤーのランキングを幅広く提供し、コントローラ/ビューの構築このモデルを使用しています(例:「トップ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のクエリガイドで何も見ていない。
私はあなたの答えの 'sort_by'バージョンを試してみました。 'sort_by'は昇順に並べ替えるので、.sliceの後に.reverseを追加して、「降順で上位10位」の結果を得なければなりませんでした。ありがとう! –
私もあなたの答えで最後の/ DBオプションを試しました:Player.select(...それはまた働いた。ありがとうもう一度。 –