使用 Ruby on Rails 创建前 5 名排行榜
我网站上的用户每当其关注者之一点击他们发布的链接时都会获得积分。现在我可以使用以下方法显示每个人的列表,
@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>
如何让该块遍历所有用户,然后只显示前 5 位?使用break if 方法不起作用。
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 display the top 5? Using the break if method is not working.
怎么样:
或者通过否定
sort_by
来完全消除相反的情况:或者您可以让数据库为您进行排序:
How about:
Or do away with the reverse altogether by negating the
sort_by
:Or you can have the database do the sorting for you: