【发布时间】: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