在Active Record中按频率排序结果

时间:2014-07-23 03:36:04

标签: ruby-on-rails ruby rails-activerecord

我是Rails和Active Record查询的新手。我想按频率订购我的查询结果。

作为SQL查询,它是:

SELECT author FROM books GROUP BY author ORDER BY COUNT(*) DESC LIMIT 10;

(我找到了here并且非常有助于制定这个问题。)

我现在所拥有的将按字母顺序排列:

<p>The authors are: <% @books.select(:author).distinct.order(:author).each do |book| %>
  <br><%= book.author %> <%= @books.where(author: book.author).count %>
<% end %></p>

这会得到我,例如:

  

Asimov,Isaac 2

     迪克,菲利普K. 8

     

Pynchon,Thomas 3

等。 但我想按频率(迪克,品钦,阿西莫夫)订购结果,而不是按字母顺序排列。

如果可能的话,我希望将作者姓名和书籍数量保留为单独的输出(希望能够将其切换到表格),尽管我确信这是获得频率的更好方法在输出中(而不是@books.where(author: book.author).count)。但主要问题是正确的初始订购。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:3)

试试这个

Book.group("author").order("count_author desc").count("author")

所以你的观点看起来像

<% @books.group("author").order("count_author desc").count("author").each do |author, count| %>
  <br><%= author %> <%= count %>
<% end %></p>

答案 1 :(得分:2)

使用下面的示例查询和生成的sql

Task.group(:project_id).limit(10).count(:id)
SELECT COUNT(`tasks`.`id`) AS count_id, project_id AS project_id FROM `tasks` GROUP BY project_id LIMIT 10
Output: {18=>1206, 22=>82, 23=>25, 25=>77, 29=>1, 35=>1, 42=>30, 44=>1, 45=>17, 53=>12}

根据惯例,您可以看到rails使用count_<column name>进行计数。您可以使用此约定按该计数排序。

Task.group(:project_id).limit(10).order('count_id DESC').count(:id)
SELECT COUNT(`tasks`.`id`) AS count_id, project_id AS project_id FROM `tasks` GROUP BY project_id ORDER BY count_id DESC LIMIT 10
Output: {145=>1949, 105=>1535, 18=>1206, 141=>738, 23804=>667, 9892=>524, 196=>478, 26969=>338, 24119=>330, 28047=>300}

实现您想要实现的目标的更好方法是在控制器中准备变量并在视图中访问它们

# controller
@counts = Book.group(:author).order('count_id DESC').count(:id)

# view
<% @counts.each do |author, count| %>
  <%= author %> <%= count %>
<% end %>
上面的

@counts包含一个哈希,其中键是作者,值是该作者的书籍计数。