rails,ruby,如何计数和排序,显示最高结果 [英] rails, ruby, how to count and sort, display top results

查看:22
本文介绍了rails,ruby,如何计数和排序,显示最高结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

认为我在这里有一个简单的问题:

Think I have a simple question here:

我有一个用户模型和一个发布模型.用户有很多帖子,帖子属于用户.我想按用户计算帖子总数并显示帖子最多的前 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!

推荐答案

先这样查询数据库:

@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.

这篇关于rails,ruby,如何计数和排序,显示最高结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆