I am looking for an answer that will return an array of user objects through (preferably) named_scope or through a class method in the User model that does some manipulation.
So, without further ado ...
I have two tables: users and fights.
- The user has many fights (has_many: fights ,: foreign_key => 'challenger_id or challengee_id')
- The fight belongs to the user (belongs to_to: challenger ,: class_name => 'User' ... belongs toto: challengee ,: class_name => 'User')
The fight has the following columns of concern:
- challenger_id (user_id fk)
- challengee_id (user_id fk)
- challenger_won (boolean)
As you can see, the user can be a challenger or a challenge, but not both.
- If the user is the challenger and challenger_won = true, then he is considered a victory.
- If the user is a challenge, and challenger_won = false, then it is considered a victory.
- If challenger_won = null, just ignore it.
I have the original SQL statement that returns the fighter attribute (user_id), grouped by most win attributes:
SELECT a.fighter, COUNT(*) AS wins
FROM (SELECT challenger_id AS fighter
FROM fights
WHERE challenger_won = TRUE
UNION ALL
SELECT challengee_id AS fighter
FROM fights
WHERE challenger_won = FALSE
) AS a
GROUP BY a.fighter;
So, given this information, how can I return an array of user objects through (preferably) named_scope or through a class method in the User model that does some manipulation?
source
share