ActiveRecord 条件顺序子句

ActiveRecord conditional order clause

我需要对任务列表进行排序:

|----------------------------------------------------------------------|
| title                            | priority    | due_at              |
| ---------------------------------|-------------|---------------------|
|  Mow the lawn                    |           1 | 2011-09-11 22:00:00 |
|  Call mom                        |           3 | 2010-01-26 09:29:03 |
|  Bake a cake                     |           2 | 2013-09-13 08:45:37 |
|  Feed the cat                    |           2 | 2015-09-12 16:03:51 |
|  Remember you don't like the cat |           2 | 2014-03-19 23:00:00 |
|----------------------------------------------------------------------|

order 子句应按优先级对逾期任务排序,所有其他按 due_at 排序,例如结果顺序应该是

如果您只需要存储在 @tasks 中的任务数组,您可以这样做:

@tasks = Task.where(due_at: 10.years.ago..Time.now).order(:priority)
@tasks += Task.where.not(due_at: 10.years.ago..Time.now).order(:due_at)

如果您需要 Task::ActiveRecord_Relation,您必须这样做:

Task.where(id: Task.where(due_at: 10.years.ago..Time.now).
               order(:priority).pluck(:id) + 
               Task.where.not(due_at: 10.years.ago..Time.now).
               order(:due_at).pluck(:id))

我最终得到以下结果(普通 SQL,尚未翻译成 AR):

SELECT *
FROM tasks 
ORDER BY 
    due_at <= Now() DESC,
    CASE due_at <= Now()  WHEN true THEN priority END ASC,
    CASE due_at <= Now()  WHEN true THEN due_at END ASC,
    CASE due_at <= Now()  WHEN false THEN due_at END DESC,
    CASE due_at <= Now()  WHEN false THEN priority END ASC