title: Rails activerecord : sum, max and joins
body: <p>I have two models <code>users</code> and <code>posts</code>. An user can votes and views a post</p>
  
  <pre><code>#users
    id
    name
  
  #posts
    id
    count_votes
    count_views
    users_id
    created_at
    updated_at
  </code></pre>
  
  <p>I want the user who received the most votes and views on his posts from the last 24 hours. The biggest sum of views and votes win.</p>
  
  <p><strong>WHAT I TRIED</strong>
  I have this SQL query, it's good but I would like to have the user with the max of votes, this one give me all users and I don't know how to add count_views</p>
  
  <pre><code>select u.name as "Name", sum(p.count_votes)
  from posts p 
  inner join users u on p.user_id = u.id 
  where p.created_at &gt;= DATE_SUB(NOW(), INTERVAL 1 day)
  group by user_id;
  </code></pre>
  
  <p>ActiveRecord version</p>
  
  <pre><code>Post.select("users.id, sum(posts.count_votes) as nb_votes")
  .joins(:user).where("posts.created_at &gt;= ?", 1.day.ago.beginning_of_day)
  .group("posts.user_id")
  
  # Results on IRB
  =&gt; #&lt;ActiveRecord::Relation [#&lt;Post id: 1&gt;, #&lt;Post id: 3&gt;]&gt; 
  </code></pre>
  
  <p>How can I combine a sum and a max on these two sums ? Is there a way to have an activerecord code or only raw SQL ?</p>