I have three models User, Game and Point where a user gets points for playing games. What I'm trying to do is display the users with the most points for the most popular games in a view.
I used this question to determine the most popular games. So I now have this scope in 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)
In my controller, I have this:
@most_popular_games = Game.most_popular_games
My models:
Models
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
However, what I can't figure out what to do is create a way to now total the points per user for each of these games and make it so I identify each game differently, so I segment them out on the view (ie show the results separately for each game).
I tried adding this in the code, but I wasn't sure of the best way to make each game's results be identifiable in the view:
@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
My question is basically how do I reuse the results for "most_points_for_popular_game" - which is the users with the most points for a given game - for each of the five games (@most_popular_games = five results)?