我有一个特定的订单,我想在其中显示我的一些博客文章,但我也希望在这些博客帖子之后显示常规博客帖子。
所以,假设我有帖子[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。是否可以在一个查询中执行此操作?
你可以按案件排序......
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进行更正)