我想提取我的Product.where(in_stock: 0)
和Product.where.not(in_stock: 0)
。然后,我想按price ASC
对集合的每个部分进行排序,并将它们连接在一起,以便首先显示库存中排序的项目,然后显示脱销的项目。
应该有适用于AR关系的有效.merge
,但它在Rails 5.2.X上不起作用
此外,Rails5在按it排序数组查找方面做得很好,但它返回的是Array
而不是AR关系。
有没有办法写出干净和可维护的工作代码?常用的Postgres
变通方法会在包含> 100个实例的集合中失败。
有没有关于如何用纯SQL实现它的想法?
发布于 2020-09-23 09:58:26
使用ORDER
在1个查询中获取它怎么样?
ORDER BY case in_stock when 0 then 2 else 1 end, net_price ASC
这将把所有in_stock: 0
记录推到底部。
要使用AR查询,请执行以下操作
Product.all.order(Arel.sql("ORDER BY case in_stock when 0 then 2 else 1 end, net_price ASC"))
我使用Arel.sql
是因为有一个不推荐使用的警告:
Dangerous query method (method whose arguments are used as raw SQL) called with non-attribute argument(s)
https://stackoverflow.com/questions/64018881
复制相似问题