Creating a top 5 Leaderboard with Ruby on Rails
Users on my site gain points everytime one of their followers clicks on a link they posted. Right now I am able to show a list of everyone by using,
@users = User.all
<table>
<tr>
<th>User</th>
<th>Points</th>
</tr>
<% @users.sort_by{|u| u.clicks.size }.reverse.each do |u| %>
<tr>
<td><%= u.name %></td>
<td><%= u.clicks.size %></td>
</tr>
<% end %>
</table>
How can I have the block go through all the users then only 开发者_Go百科display the top 5? Using the break if method is not working.
How about:
@users.sort_by{|u| u.clicks.size }.reverse[0...5].each do |u|
Or do away with the reverse altogether by negating the sort_by
:
@users.sort_by{|u| -u.clicks.size }[0...5].each do |u|
Or you can have the database do the sorting for you:
@users = Users.joins(:clicks).order("clicks.size DESC").limit(5)
精彩评论