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

查看:287
本文介绍了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.

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

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