对Rails进行排序按特定顺序查询结果并将其余部分添加到其中

问题描述 投票:0回答:1

我有一个特定的订单,我想在其中显示我的一些博客文章,但我也希望在这些博客帖子之后显示常规博客帖子。

所以,假设我有帖子[1,7,35,36,48],我想先发帖:

@selected_posts = Post.find([1, 7, 35, 36, 48])

但现在我需要查询其他所有帖子,不包括上述内容:

@other_posts = Post.where.not(id: [1, 7, 35, 36, 48])

现在我需要结合这些来维持这个顺序:

Post.find([1, 7, 35, 36, 48]) + Post.where.not(id: [1, 7, 35, 36, 48])

我正在使用Postgres。是否可以在一个查询中执行此操作?

ruby-on-rails postgresql
1个回答
1
投票

你可以按案件排序......

priority_ids = [1, 7, 35, 36, 48]

@all_posts = Post.all.order("CASE WHEN id IN (#{priority_ids.join(',')}) THEN 1 ELSE 2 END")

(感谢@DeepakMahakale进行更正)

© www.soinside.com 2019 - 2024. All rights reserved.