vendredi 22 mai 2020

Rails 3: Given a player, find the number of times they have been paired with each opponent

I am using Rails 3.2. My schema is quite more complex but simplifying, I have Pcs (representing players), Games and Projects such that:

class Game < ActiveRecord::Base
   has_many :projects

class Pc < ActiveRecord::Base
   has_many :projects

class Project < ActiveRecord::Base
   has_many :games
   belongs_to :pc

note: there's a table for GameProject as well for the many-to-many association.

I am trying to find a query (ActiveRecord is preferred over fully raw SQL) such that, given a Pc, returns the number of games each one of the other Pcs has played against them. A Pc has played against another one if there are project(s) of the two of them in the same game. An example situation would be:

+------+---------+----+
| Game | Project | Pc |
+------+---------+----+
|    1 |       1 |  1 |
|    1 |       2 |  1 |
|    1 |       3 |  1 |
|    1 |       4 |  2 |
|    1 |       5 |  2 |
|    2 |       6 |  1 |
|    2 |       7 |  2 |
|    3 |       8 |  1 |
|    3 |       9 |  3 |
+------+---------+----+

If I want to find out how many times each opponent has played against Pc1, the result should be:

{2 => 2, 3 => 1}

As Pc2 has played in two games with Pc1 and Pc3 has played only once with Pc1. I don't care if Pc1 itself appears in the result, I'll just not process it afterwards.

The same query for Pc2 should return:

{1 => 2, 3 => 0}

As Pc1 has played twice with Pc1 and Pc3 has not played in any game with Pc2.

I've been trying for a while but I can't seem to get it right.

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire