问题
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