Complex queries using Rails query language

Posted by Daniel Johnson on Stack Overflow See other posts from Stack Overflow or by Daniel Johnson
Published on 2010-05-25T22:32:23Z Indexed on 2010/05/26 0:41 UTC
Read the original article Hit count: 318

I have a query used for statistical purposes. It breaks down the number of users that have logged-in a given number of times. User has_many installations and installation has a login_count.

select total_login as 'logins', count(*) as `users` 
  from (select u.user_id, sum(login_count) as total_login 
          from user u 
               inner join installation i on u.user_id = i.user_id
               group by u.user_id) g
  group by total_login;

+--------+-------+
| logins | users |
+--------+-------+
| 2      |     3 |
| 6      |     7 |
| 10     |     2 |
| 19     |     1 |
+--------+-------+

Is there some elegant ActiveRecord style find to obtain this same information? Ideally as a hash collection of logins and users: { 2=>3, 6=>7, ...

I know I can use sql directly but wanted to know how this could be solved in rails 3.

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about activerecord