开发者

MySQL statement convert to pretty Rails AR Statement?

开发者 https://www.devze.com 2023-01-20 18:07 出处:网络
I have a MySQL statement that took me all night to come up with.I\'m wondering if this thing can be converted from a direct call to something pretty like Object.find(:conditions)

I have a MySQL statement that took me all night to come up with. I'm wondering if this thing can be converted from a direct call to something pretty like Object.find(:conditions)

    ActiveRecord::Base.connection.execute("
    SELECT *, 
      (SELECT COUNT(*) 
      FROM scores AS temp2 
      WHERE temp2.score > scores.score 
      ORDER BY score DESC) + 1 AS rank 
    FROM scores 
    WHERE user_id=%s 
    ORDER BY score DESC" 
    % user_id).fetch_hash

This statement is part of a high score website built for a Android game. It gets the top high score and has a subquery that gives it the rank as well.

Can this be made into something nicer? Also, is this the most eff开发者_高级运维icient method of going about this?

Thanks, Justin


This should do it for you:

user = Score.find_by_user_id(id)
rank = Score.count(:conditions => ['score > ?', user.score]) + 1
0

精彩评论

暂无评论...
验证码 换一张
取 消