ActiveRecord条件顺序子句

ActiveRecord条件顺序子句,activerecord,conditional,Activerecord,Conditional,我需要对任务列表进行排序: |----------------------------------------------------------------------| | title | priority | due_at | | ---------------------------------|-------------|---------------------| | Mow the lawn

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

|----------------------------------------------------------------------|
| 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子句应按优先级对过期任务进行排序,其他所有任务应按到期时间进行排序,例如,生成的订单应为

  • 修剪草坪
  • 烤蛋糕
  • 打电话给妈妈
  • 记住你不喜欢猫
  • 喂猫

若您只需要存储在
@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)
如果需要
任务::ActiveRecord\u关系
,则必须执行以下操作:

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