[help] how to get the nth record for each record owner. Query question.

Help

I have two models, player and game. player has_many games, and each game belongs to a player. How do I get the nth game belonging to each player?

In actuality I am trying to get the nth last according to another column (games_played) but if I figure out the above question I should be good. I tried to use

Game.group(:player_id).having('games_played=MAX(games_played))

which does work for the last

record in each group, however

Game.group(:player_id).having('games_played=MAX(games_played)- n)

where n is replace by a number does not work. It seems group takes only one record from each group?

Posted Jul 16, 2017, 9:17 PM UTC · edited

310
Loading comments…