让我用简单的例子来描述。
我有一个数字列表:
例如:list = [ 3, 1, 2 ]
我在数据库中有一个名为 Products
的表,其中有 3 行,product_id
= 1
、2
和 3
。
现在我需要查询Products
按list
值排序(3,1,2)
因此结果将是:
product_3product_1product_2
查询将如下所示:product.sort(list) or product.order(list) 或其他一些替代请
这应该适合您:
list = [3, 1, 2]
Product.where(product_id: list).sort_by { |p| list.find_index(p.product_id) })