rails,ruby,如何计数和排序,显示顶部结果
想想我在这里有一个简单的问题:
Think I have a simple question here:
我有一个用户模型和一个Post模型。用户有很多帖子,帖子属于User。我想计算用户的帖子总数,并显示最多帖子的前10个用户。这里是我到目前为止的代码:
I have a User Model, and a Post Model. Users has many posts, and posts belong to User. I want to count the total number of posts by user and display the top 10 users with the most posts. Here is the code I have so far:
控制器:
@users = User.all
查看:
<% @users.sort.each do |user| %>
<%= user.username %>: <%= user.posts.count(:group => 'user_id') %><br>
<% end %>
这会得到每个用户的帖子总数,我明白为什么这种情况发生,但不知道如何我可以改变它按计数排序。
This gets me the total posts per user, but sorts by username. I understand why this is happening, but not sure how I can change it to sort by the count instead. Any help would be greatly appreciated!
首先查询数据库,如下所示:
First query the database like this:
@posts_per_user_count = Post.joins(:user).group(:user).order('count_all DESC').limit(10).count
这将导致一个哈希,其中包含具有结果的数组。然后在你的视图中,你可以这样迭代:
This is going to result in a hash, which contains arrays with your result. Then in your view you can iterate over it like this:
<% @posts_per_user_count.each do |item| %>
<%= item[0].username %>: <%= item[1].to_s %><br>
<% end %>
请参阅anonymousxxx的答案。他正在使用计数器。这比以我的方式查询数据库更有效。
Please also see the answer from anonymousxxx. He is using the counter. This is more efficient than query the database in the way I do.