ruby-on-rails - 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
解决方案
Box.left_joins(:breed_cycles)
.group(:id)
.order('MAX(breed_cycles.breed_start_date) DESC NULLS LAST')
Box.left_joins(:breed_cycles)
.group(:id)
.order(BreedCycle.arel_table[:breed_start_date].maximum.desc.nulls_last)
推荐阅读
- laravel - Custom login property Laravel 8
- php - Get week range with timezone
- python - Pygame window closes right after
- kubernetes - Is there any way to know when a PVC is mounted last time in k8s?
- flutter - how to solve "Execution failed for task ':app:compileFlutterBuildDebug"
- azure - Azure 静态网站使用我自己的 ssl 证书?
- r - 绘制瑞利商的等高线图以验证函数的最小值和最大值
- node.js - 使用 typescript 定义来验证 POST 正文请求
- javascript - 全局 onclick 处理程序与每个元素事件处理程序
- javascript - 4000 毫秒后重试超时:无法读取未定义的属性(读取“toLowerCase”)