Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You're on the right track. Seems like you would be better off using the <code>all</code> command with the count condition within it as opposed to the <code>count</code> command. Something like this:</p> <pre><code>Point.all(:select =&gt; 'user_id, count(id) as point_count', :group =&gt; :user_id, :conditions =&gt; { :correct =&gt; 'yes' }, :order =&gt; 'point_count desc', :limit =&gt; 10) </code></pre> <p>This will return 10 limited <code>Point</code> objects with a <code>user_id</code> attribute (so you can still access the <code>user</code> relationship), and a <code>point_count</code> attribute with the number of correct points said user has obtained.</p> <p>Note: you could change the limit to be however many users you wanted to display in your leaderboard. This example would return 10.</p> <p>It might make more sense to have your code look like this:</p> <pre><code>@points = Point.all(:select =&gt; 'user_id, count(id) as point_count', :group =&gt; :user_id, :conditions =&gt; { :correct =&gt; 'yes' }, :order =&gt; 'point_count desc', :limit =&gt; 10) </code></pre> <p>And as I said in a comment below, you could iterate through them by doing something like this (this would assume that your <code>User</code> model has a name attribute):</p> <pre><code>&lt;table&gt; &lt;% @points.each do |point| %&gt; &lt;tr&gt; &lt;td&gt;&lt;%= point.user.name %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= point.point_count %&gt;&lt;/td&gt; &lt;/tr&gt; &lt;% end %&gt; &lt;/table&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload