【问题标题】:Ordering by datetime for nested objects using PostgreSQL使用 PostgreSQL 按日期时间排序嵌套对象
【发布时间】:2019-06-25 08:09:58
【问题描述】:

我想按照帖子创建或更新的频率对我的图板进行排序。我已经能够做到这一点,但 exact 排序仍然关闭。例如,如果我有 2 个帖子(A、B)和更新 B,则该帖子仍然排在 A 之后。我之前在 PostgreSQL 中遇到过这个问题,并使用对象的 id 作为辅助排序列来解决它。不幸的是,在这种情况下,我将通过帖子进行。根据我的代码,问题似乎是什么?

class Board < ApplicationRecord
  has_many :posts
end

class Post < ApplicationRecord
  belongs_to :board
end

class StaticController < ApplicationController
  def index
    @active_boards = Board
      .includes(:posts)
      .where.not(posts: { board_id: nil })
      .order('posts.created_at ASC', 'posts.updated_at ASC')
      .limit(10)
  end
end

【问题讨论】:

  • 为什么不按 updated_at 排序,因为无论记录是创建还是更新都会设置。
  • order('posts.created_at ASC', 'posts.updated_at ASC') 表示如果两个帖子共享完全相同的created_at,则使用updated_at 打破平局。 @PaulByrne 提出的建议将在创建记录时生效,created_at == updated_at

标签: ruby-on-rails postgresql datetime activerecord sql-order-by


【解决方案1】:

第一种可能性是在插入帖子时也设置updated_at,然后您可以简单地使用该列。

另一个选项是ORDER BY max(created_at, updated_at)

【讨论】:

  • "第一种可能性是在插入帖子时也设置 updated_at,然后您可以简单地使用该列。"这不就是我现在正在做的吗?
  • 你不显示... 一个简单的方法是将列定义为updated_at timestamp with time zone DEFAULT current_timestamp 并且不向该列插入任何内容,以便使用默认值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-06
  • 2016-02-19
  • 1970-01-01
  • 2021-03-01
  • 1970-01-01
  • 2019-07-05
相关资源
最近更新 更多