Rails, ActiveRecord, query id in array of ints, ke

2020-05-19 00:14发布

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)

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.

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.

Thanks!

7条回答
Bombasti
2楼-- · 2020-05-19 00:52

regard less of MySQL and Postgresql, if you have a small size of ids,

User.where(id: ids).sort_by { |u| ids.index(u.id) }
查看更多
登录 后发表回答