首页 > 解决方案 > Rails 按来自 has_many 关联的最后一条记录的属性排序

问题描述

我有两个具有 belongs_to 和 has_many 关系的模型。BreedCycle 具有breed_start_date日期时间属性。我要做的是boxes按最新(最后创建的)品种周期的breed_start_date属性进行排序。长话短说,我的目标是编写查询,按breed_cycles.breed_start_date属性提取所有最新的品种循环的盒子和订单盒子。也breed_start_date可以为零,所以我需要NULLS LAST选项。非常感谢任何帮助(链接到文档、示例等)。

class Box < ApplicationRecord
  has_many :breed_cycles
end

class BreedCycle < ApplicationRecord
  belongs_to :box
end

标签: ruby-on-railspostgresql

解决方案


Box.left_joins(:breed_cycles)
   .group(:id) 
   .order('MAX(breed_cycles.breed_start_date) DESC NULLS LAST')

或者在 Rails 6.1+ 中使用 Arel

Box.left_joins(:breed_cycles)
   .group(:id)
   .order(BreedCycle.arel_table[:breed_start_date].maximum.desc.nulls_last)

推荐阅读