使用PostgreSQL按日期时间对嵌套对象进行排序

时间:2019-01-31 19:18:58

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

我想按创建或更新帖子的频率对董事会分类。我已经可以执行此操作,但是精确的订购仍然处于关闭状态。例如,如果我有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

1 个答案:

答案 0 :(得分:2)

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

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

相关问题