代码之家  ›  专栏  ›  技术社区  ›  Carl Edwards monkbroc

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

  •  0
  • Carl Edwards monkbroc  · 技术社区  · 7 年前

    准确的 订单仍在关闭中。例如,如果我有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 回复  |  直到 7 年前
        1
  •  2
  •   Laurenz Albe    7 年前

    第一种可能性是也设置 updated_at 插入帖子后,您只需使用该列即可。

    ORDER BY max(created_at, updated_at) .