Rails: Query to sort record by number except 0

感情迁移 提交于 2019-12-31 05:06:09

问题


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

Below is the Rails Query:

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

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]

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]

回答1:


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)

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")


来源:https://stackoverflow.com/questions/47041475/rails-query-to-sort-record-by-number-except-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!