나는 선수 순위의 폭 넓은 선택을 제공하는 컨트롤러/뷰 짓고 있어요이 모델을 사용 (예 : "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 쿼리 가이드에서 이와 같은 것을 보지 못했습니다.
답변의 'sort_by'버전을 시도해 보았습니다. 'sort_by'는 오름차순으로 정렬되므로 .slice 다음에 .reverse를 추가하여 "내림차순으로 상위 10 개"결과를 얻었습니다. 감사! –
나는 또한 당신의 대답에 마지막/DB 옵션을 시도했다 : Player.select (... 그것은 또한 일했다. 다시 한번 감사드립니다. –