我有一个活跃职位的索引。目前,它们按最近的排序,即 created_at
。但是,最近我添加了一个续订功能,可以更新 renewal_date
属性而不更新 created_at
。
我想要实现的是使用 renewal_date
和 created_at
对列表进行降序排序。
jobs = Job.where(active: true).reorder("renewal_date DESC NULLS LAST", "created_at DESC")
使用此代码,无论创建多少新作业,更新的作业将始终位于顶部。我如何对其进行排序,以便它检查两个属性的日期并根据最近的日期对其进行排序?
最佳答案
您的代码将首先按 renewal_date 排序,末尾为空值,然后如果两条记录具有相同的 renewal_date,则查看 created_at。
我假设您想要做的是类似于“max(renewal_date, created_at)”的操作,它将采用“最后修改日期”或另一种自定义方式来比较这两个字段。 如果是这样,您可以在这里找到答案:merge and order two columns in the same model
Job.where(active: true).reorder('GREATEST(renewal_date, created_at) DESC')
关于ruby-on-rails - Rails 中的 PostgreSQL : sorting object by two date attributes in descending order,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35585081/