我正在用 Rails 创建一个基本论坛。我有一个有很多主题的论坛,主题有很多帖子。我想获取特定论坛的所有主题,并以第一个是具有最新帖子的主题的方式对它们进行排序。
在我的帖子存储库中,我有一个方法可以返回最新的帖子。
def latest_post
order('created_at DESC').limit(1).first
end
在 Threads 类中,我有一个方法调用 latest_post 返回最新的帖子
def latest_post
self.posts.latest_post
end
我按以下方式使用该方法来获取线程的最新帖子。
@some_thread.posts.latest_post
现在我想获取线程的有序列表。我尝试向 Thread 类添加一个默认范围,以便在默认情况下对它们进行排序。
default_scope order('latest_post.created_at DESC')
这没有用。我相信是因为订单的 latest_post 部分不在数据库级别。
如何根据最新帖子的创建日期对主题进行排序。它不需要是默认顺序。
最佳答案
试试这个:
scope :latest_post_first , Thread.joins(:posts). # joins needed to access posts for each thread
# grouping enables the SQL MAX function
# also returns unique threads
group("threads.id").
# order by maximum value of post's created_at in each group
# i.e. each thread since grouping is by thread id
order("MAX(posts.created_at) DESC")
请注意,这只会返回至少有一篇帖子的线程,因此我不建议将其设为默认范围。
关于ruby-on-rails - 根据 child 的创建日期对对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19399426/