【发布时间】:2014-09-22 10:26:42
【问题描述】:
我正在编写一个允许用户为图片评分的应用程序。我正在尝试创建一个表格,根据它们包含的特色图片的数量对类别进行排序。例如,它看起来像这样。
CATEGORY FEATURED IMAGES
Landscapes 5
Animals 3
Forests 2
Oceans 2
Sunsets 1
在上面,每个类别都按其包含的特色图片数量排序。如果多个类别共享相同数量的特色图像,则这些类别按字母顺序列出(例如:森林、海洋)。
Featured image: An image with a star rating of 4 or higher.
我尝试了以下
Picture.order(stars: :desc).where('stars >= 4').order(category: :asc)
这里我按星数(评分)对每张图片进行排序,我只想选择星数至少为 4 的图片。然后我按类别排序。
我也试过
Picture.where(category: 'Landscapes').where('stars >=4').count
=> 5
我首先需要为至少包含 1 张特色图片的每个类别找到答案。
array = []
array.push(Picture.where(category: 'Landscapes').where('stars >=4').count)
=> 5
array.push(Picture.where(category: 'Animals').where('stars >=4').count)
=> 3
array.push(Picture.where(category: 'Forests').where('stars >=4').count)
=> 2
array.push(Picture.where(category: 'Oceans').where('stars >=4').count)
=> 2
Picture.where(category: 'Sunsets').where('stars >=4').count
=> 1
array
=>[5,3,2,2,1]
这成功地按照特色图片的数量对类别进行了排序,但似乎效率低下。
然后我可能会尝试这样的事情
<tbody>
<% Picture.where('stars >= 4').each do |picture| %>
<tr>
<td><%= Picture.category %></td>
<td><%= array[num]] %></td>
</tr>
<% end %>
</tbody>
获取第一个代码黑色的外观。
有什么方法可以将该查询存储在一个循环中,以便快速找到所有类别的这些值?
我知道 Ruby 方法 sort 和 sort_by,但是如何使用它对上述查询的结果进行排序。
基本上,我想按类别包含的特色图片数量对类别进行排序。我想要类别名称,然后是它们旁边的特色图片数量。
【问题讨论】:
标签: sql ruby-on-rails ruby sorting