Rails,ActiveRecord,在整数数组中查询id,保持传递数组的顺序 [英] Rails, ActiveRecord, query id in array of ints, keep order of passed array

查看:42
本文介绍了Rails,ActiveRecord,在整数数组中查询id,保持传递数组的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑问题的最佳解决方案.假设我们有一个 ActiveRecord 模型的 id 列表:

I am thinking about the best solution for a problem. Let's say that we have a list of ids of ActiveRecord model:

ids = [1, 100, 5, 30, 4, 2, 88, 44]

然后我想进行查询,例如从列表中选择所有用户,但要保持顺序.如果我这样做

Then I would like to make query that selects all users for example with ids from the list but to keep the order. If I do

User.where(id: ids)

响应将是按 id 排序的用户列表,但我希望顺序与数组中的顺序相同.

the response will be a list of users with asc order by id, but I want the order to be the same as in the array.

您认为这里的最佳解决方案是什么?选择所有用户然后操作ActiveRecord 对象列表?也许有更聪明的方法来做到这一点.

What do you think that it's the best solution here? Select all users and then to manipulate the list of ActiveRecord objects? Maybe there is a more clever way to do that.

谢谢!

推荐答案

参考这里,对于 postgresql,

With reference to here, for postgresql,

User.where(id: ids).order("position(id::text in '#{ids.join(',')}')")

这篇关于Rails,ActiveRecord,在整数数组中查询id,保持传递数组的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆