Rails:查询按除 0 以外的数字对记录进行排序 [英] Rails: Query to sort record by number except 0

查看:35
本文介绍了Rails:查询按除 0 以外的数字对记录进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我根据优先级(升序)排列数据,其中0"在优先排序时被忽略.

I'm arranging the data based on a priority(ascending order), where '0' ignored in prioritising.

下面是 Rails 查询:

Below is the Rails Query:

Profile.where(active: true).order(:priority).pluck(:priority)

此查询返回优先级从0"开始的记录的有序列表

This query returns an ordered list of records with priorities that starts from '0'

[0, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 7]

您能帮我弄清楚如何按照下面的示例对查询中添加了0"记录的数据进行排序.

Could you help me figure out how to order the data where the record with "0" is added to last in the query as per the example below.

Example: [1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 7, 0]

推荐答案

您可以将字符串传递给 #order 以使用原始 SQL,因此您可以说:

You can pass a string to #order to use raw SQL so you could say:

Profile.where(active: true)
       .order('case priority when 0 then 1 else -1 end, priority')
       .pluck(:priority)

强制优先级为零的条目结束.当然,您不必使用 1-1 作为数字,您可以使用任何您可以阅读并按正确顺序排序的内容,您甚至可以使用字符串(当然假设它们排序正确):

to force the priority zero entries to the end. You don't have to use 1 and -1 as the numbers of course, you could use anything that is readable to you and sorts in the right order, you could even use strings (assuming they sort properly of course):

.order("case priority when 0 then 'last' else 'first' end, priority")

这篇关于Rails:查询按除 0 以外的数字对记录进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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