I'm looking for an answer that will return an array of user objects via (preferably) a named_scope or via a class method on the User model that does some manipulation.
So without further ado...
I have two tables: users and fights.
Fight has the following columns of concern:
As you can see, a user can be a challenger or a challengee, but not both.
I have a raw SQL statement that returns a fighter attribute (the user_id) grouped by most wins attribute:
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 info, how can I return an array of user objects via (preferably) a named_scope or via a class method on the User model that does some manipulation?
I think you can try something like this to recreate the result of you query:
class User
named_scope :winners,
:select => 'users.*, COUNT(fight.id) AS wins',
:join => :fights,
:conditions => ['(fights.challenger_id = user_id AND fights.challenger_won = TRUE) OR (fights.challengee_id = user_id AND NOT fights.challenger_won = FALSE)']
:group => 'user_id'
end
However, for caching puposes, you might want to consider adding a win_count field to the User model. If you create a setter method for the winner of a fight, you can increment the win_count right at that moment when it changes.
Or, without the join (mysql specific)
class User
named_scope :winners,
:select => 'if(challenger_won = FALSE,challenger,challengee) as winner,COUNT(id) AS wins ',
:group => 'user_id'
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.