2013-03-12 59 views
1

我有三種模式用戶,遊戲和點,其中用戶獲得積分玩遊戲。我想要做的是在視圖中顯示用戶最熱門的遊戲點數。識別導軌查詢結果

我用這個question來確定最流行的遊戲。所以,我現在有這個範圍,Game.rb:

scope :most_popular_games, 
    select("games.id, name, count(points.id) AS points_count"). 
    joins(:points). 
    group("games.id"). 
    order("points_count DESC"). 
    limit(5) 

在我的控制,我有這樣的:

@most_popular_games = Game.most_popular_games 

我的模型:

模型

class Point < ActiveRecord::Base 
    belongs_to :game 
    belongs_to :user 
end 

class Game< ActiveRecord::Base 
    has_many :points 
end 

class User < ActiveRecord::Base 
    # no relationship for points or games 
end 

class GameRank < ActiveRecord::Base 
    belongs_to :game 
    belongs_to :user 
end 

然而,我無法弄清楚該做什麼是創建一種方法,現在爲每個用戶分配這些遊戲中的每個用戶的積分,並使其成爲我識別每個用戶我有所不同,所以我將它們分解在視圖上(即分別顯示每場比賽的結果)。

我試圖在代碼中添加這一點,但我不知道的,使每場比賽的結果在視圖中可識別的最佳方式:

@most_popular_games.each do |most_popular_game| 
    most_points_for_popular_game = GameRank.where("game_id =?", most_popular_game.id).order('total_points desc').limit(10) 
end 

我的問題是基本上我怎麼重新使用「most_points_for_popular_game」的結果 - 這是針對給定遊戲得分最高的用戶 - 對於五場比賽(@mo​​st_popular_games =五次結果)中的每一場?

+0

也許嘗試給模型關係看,所以它可以在不SQL來完成。關係是什麼?一個用戶一次玩一個遊戲,或者兩個用戶可以玩一個遊戲,或者一個用戶只能玩一次遊戲? – Zippie 2013-03-12 23:37:36

+0

我已經添加了模型。謝謝 – yellowreign 2013-03-12 23:48:29

+0

用戶只能玩一次遊戲嗎? – Zippie 2013-03-12 23:52:30

回答

0

共忽略N + 1次的查詢和附加標記:

添加:game_ranks關係Game

class Game 
    has_many :game_ranks 
end 

一個範圍添加到GameRank

class GameRank 
    scope :top, order('total_points desc').limit(10) 
end 

(我根據您的示例假設GameRank上的total_points列)

在你看來:

<% @most_popular_games.each do |game| %> 
    <%= game.name %> 
    <% game.game_ranks.top.each do |rank| %> 
     <%= rank.user.name %>,<%= rank.total_points %> 
    <% end %> 
<% end %>