2012-03-23 5 views
0

나는 선수 순위의 폭 넓은 선택을 제공하는 컨트롤러/뷰 짓고 있어요이 모델을 사용 (예 : "10 리더 보드".) : 내 컨트롤러에서레일 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) 

내 접근 방식은 배열에있는 모든 선수를 얻을하고 루비의 array.sort {| a,b | block } → new_array 옵션을 사용하는 것입니다. 불행하게도 나의 빈약 한 AR 이해와 루비의 능력이 나를 실패

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은 활성 레코드가 아니며 일반적으로 오래된 루비이며 두 매개 변수가있는 블록을 사용하여 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 플레이어를 찾을 수 있습니다 10 명의 부유 한 플레이어에게 제한하는 것보다) 시도해 볼 수도 있습니다 ... (테스트 안 함)

@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 (... 그것은 또한 일했다. 다시 한번 감사드립니다. –