Rails 5.1.2
These are the two models in question.
class Person < ApplicationRecord
has_many :awards
end
class Award < Application Record
belongs_to :person
end
The Award
model has a column called rank
which can be 1
, 2
, or 3
, and a column called category
(also integers, but let's just use letters for now).
I'm trying to rank People
based on their awards
of a certain rank. Many people can have the same amount of a rank. For example, 40 people might have 30 rank 1 awards of category X.
For example:
Most Awards for Category A
People
Granted the Award
with Rank
1
8 Times
- Person 1
- Person 2
People
Granted the Award
with Rank
2
30 Times
- Person 1
- Person 7
- Person 19
People
Granted the Award
with Rank
3
60 Times
- Person 2
- Person 19
- Person 44
I want to build a query that returns a collection of People
.
Logically, this is what my query should do (in pseudo code):
Get all `people` who have the maximum `count` of awards where `awards.category` is `A` and `awards.rank` is `1`.
...and repeat this for rank 2
and rank 3
.
A counter_cache would not work because of the implication of categories (unless I create a counter_cache for each category, but that feels far redundant and not flexible).
As usual, an idea that sounded simple turned out to be far more complex than I thought, and I have no idea how to pull this off.