ActiveRecord.find(array_of_ids),保留顺序 [英] ActiveRecord.find(array_of_ids), preserving order

查看:17
本文介绍了ActiveRecord.find(array_of_ids),保留顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当你在 Rails 中做 Something.find(array_of_ids) 时,结果数组的顺序不依赖于 array_of_ids 的顺序.

When you do Something.find(array_of_ids) in Rails, the order of the resulting array does not depend on the order of array_of_ids.

有什么办法可以找到并保留订单吗?

Is there any way to do the find and preserve the order?

ATM 我根据 ID 的顺序手动对记录进行排序,但这有点蹩脚.

ATM I manually sort the records based on order of IDs, but that is kind of lame.

UPD:如果可以使用 :order 参数和某种 SQL 子句指定顺序,那么如何?

UPD: if it's possible to specify the order using the :order param and some kind of SQL clause, then how?

推荐答案

答案只针对mysql

mysql 中有一个函数叫做 FIELD()

There is a function in mysql called FIELD()

以下是在 .find() 中使用它的方法:

Here is how you could use it in .find():

>> ids = [100, 1, 6]
=> [100, 1, 6]

>> WordDocument.find(ids).collect(&:id)
=> [1, 6, 100]

>> WordDocument.find(ids, :order => "field(id, #{ids.join(',')})")
=> [100, 1, 6]

For new Version
>> WordDocument.where(id: ids).order("field(id, #{ids.join ','})")

更新:这将在 Rails 6.1 中移除 nofollow

Update: This will be removed in Rails 6.1 Rails source code

这篇关于ActiveRecord.find(array_of_ids),保留顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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