ruby-on-rails - ActiveRecord 按来自多个表的列排序
问题描述
假设我有一个用户模型
class User < ActiveRecord::Base
has_many :posts
has_many :comments
...
end
Post
并且两者Comment
都有created_at
列。
如何根据created_at
两者的最新列对用户进行排序posts
和comments
使用 ActiveRecord 组合?
我知道我可以使用 Ruby 的sort
方法,但这太慢了。
解决方案
假设您使用 PostgreSQL:
# Users with most recently created posts/comments go first
User.left_outer_joins(:posts, :comments)
.group('users.id')
.order('GREATEST(MAX(posts.created_at), MAX(comments.created_at)) DESC')
# .. and go last
User.left_outer_joins(:posts, :comments)
.group('users.id')
.order('GREATEST(MAX(posts.created_at), MAX(comments.created_at)) ASC')
对于 MySQL,代码似乎是相同的。
推荐阅读
- python - Pandas 函数返回窗口长度的所有子序列
- android - 将数据从 Activity 发送到 AccessibilityService android
- delphi - 如何在 Delphi 中设置 SOAP 元素的属性?
- javascript - 样式在 nextjs 中刷新
- php - 如果没有为该选项卡提供数据,则使用 PHP 删除选项卡
- javascript - 如何通过循环对象来创建新行?
- plotly - 为什么 plotly.express line_3d 渲染很奇怪
- kivy - 带有屏幕管理器的 kivy 菜单栏和单独屏幕上的新菜单
- mariadb - 加载 csv 时出现语法错误 IGNORE 1 ROWS 和选择列
- regex - 正则表达式从右侧而不是左侧匹配