[英]Returning array of objects via named_scope — has_many…belongs_to association; UNION ALL query
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. 我正在寻找一个答案,它将通过(最好)一个named_scope返回一个用户对象数组,或者通过User模型上的类方法返回一些操作。
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: 我有一个原始的SQL语句,它返回按最多wins属性分组的战斗机属性(user_id):
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? 所以给定这个信息,如何通过(最好)一个named_scope返回一个用户对象数组,或者通过用户模型上的类方法进行一些操作?
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. 但是,对于缓存目的,您可能需要考虑将win_count字段添加到User模型。 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. 如果为战斗的胜利者创建一个setter方法,则可以在更改时立即增加win_count。
Or, without the join (mysql specific) 或者,没有连接(特定于mysql)
class User
named_scope :winners,
:select => 'if(challenger_won = FALSE,challenger,challengee) as winner,COUNT(id) AS wins ',
:group => 'user_id'
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.