Note that there are some explanatory texts on larger screens.

plurals
  1. PORails 3 - How can you sort an AR query result by doing math on attributes?
    primarykey
    data
    text
    <p>I'm building a controller/view that provides a wide selection of player rankings (e.g. "Top 10 Leader Boards".) Using this model:</p> <pre><code>class Player &lt; ActiveRecord::Base attr_accessible :name, :games_played, :games_lost, :games_won, games_exited, :total_kills, :total_deaths, :total_points, :total_coins end </code></pre> <p>In my controller I have some obvious query results to pass to my view to populate player ranking lists:</p> <pre><code>@top_winners = Player.order("games_won DESC").limit(10) @top_assassins = Player.order("total_kills DESC").limit(10) </code></pre> <p>I now need to add some sorted rankings that are calculations. Examples:</p> <pre><code>@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) </code></pre> <p>My approach is to get all the players in an array and then use Ruby's <code>array.sort {| a,b | block } → new_array</code> option. In the case of <code>@most_greedy</code> I tried this:</p> <pre><code>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) </code></pre> <p>Which generates the error:</p> <pre><code>undefined local variable or method `x' for #&lt;PlayersController:0x007fb7dac59d08&gt; </code></pre> <p>Unfortunately my meager AR understanding and Ruby skills are failing me. How can I make this approach work? Is there a different approach to this type of problem? I didn't see anything in the AR Query Guide like this.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload