【问题标题】:Active Record Querying - Sorting by the count of an attribute that meets a queryActive Record Querying - 按满足查询的属性计数排序
【发布时间】: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


    【解决方案1】:

    您可以在同一个通话中拥有多个订单。这允许您根据需要进行多列排序。这将首先做星星,然后如果有多个相同的,它将按类别排序。

    Picture.where('stars >= 4').order(stars: :desc, category: :asc)
    

    要计算每个类别中有多少,请使用 group 方法。

    Picture.where('stars >= 4').group('category').count()
    

    这应该返回一个哈希值,其中键作为类别,值作为星数 >= 4 的图片数。

    【讨论】:

    • 伟大的工作。这将返回一个记录数组。不过,我想要计算一个类别中特色图片的数量。
    • @DarkMouse 一开始我不太明白你的目的。我已经更新了我的答案。
    • 太棒了,效果很好。我会接受这个答案。
    【解决方案2】:

    我要感谢 ericsaupe 在这里帮助我。这让我得以找到解决方案。

    <tbody>
    <% Picture.where('stars >=4).group('category').count.sort_by{|key, value|value}
    .reverse.each do |picture| %>
      <tr>
        <td> <%= picture[0] %></td>
        <td> <%= picture[1] %></td>
      </tr>
      <% end %>
    </tbody>
    

    输出

    Landscapes        5
    Animals           3
    Forests           2
    Oceans            2
    Sunsets           1
    

    【讨论】:

      猜你喜欢
      • 2012-08-05
      • 1970-01-01
      • 2013-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多