用户在我的网站上为说唱歌词(示例)创建注释。我想创建一个排行榜,以奖励创建最多注释的人。
排行榜应跟踪每个用户总共创建了多少注释,以及他在过去一周、一天等时间段内创建了多少注释。
我没有问题实现总体排行榜:
@users = User.all
<table>
<tr>
<th>Contributor</th>
<th>Annotations</th>
</tr>
<% @users.sort_by{|u| u.annotations.size }.reverse.each do |u| %>
<tr>
<td><%= u %></td>
<td><%= u.annotations.size %></td>
</tr>
<% end %>
</table>
但是当我尝试实现(比如)每日得分板时,我会重复代码,操作非常缓慢(因为它必须遍历内存中的每个注释,而不能依赖数据库排序/计数):
<table>
<tr>
<th>Contributor</th>
<th>Annotations</th>
</tr>
<% @users.sort_by{|u| u.annotations.select{|a| a.created_at > 1.day.ago }.size }.reverse.each do |u| %>
<tr>
<td><%= u %></td>
<td><%= u.annotations.select{|a| a.created_at > 1.day.ago }.size %></td>
</tr>
<% end %>
</table>
如何最好地实现每日/每周的记分板?