是否ActiveRecord的find_all_by_X preserve订单?如果没有,应该用什么呢? [英] Does ActiveRecord find_all_by_X preserve order? If not, what should be used instead?

查看:173
本文介绍了是否ActiveRecord的find_all_by_X preserve订单?如果没有,应该用什么呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个非空数组 IDS 的事对象ID,我想找到对应的对象使用东西= Thing.find_all_by_id(IDS)。我的IM pression是的东西不一定有一个排序类似于 IDS

  1. 是我的即时通讯pression是否正确?

  2. 如果是这样,我可以代替 find_all_by_id 是preserves秩序和不打数据库不必要多少次?

解决方案
  1. 使用阵列#排序

检查出来:

  Thing.where(:ID => IDS).sort! {| A,B | ids.index(a.id)< => ids.index(b.id)}
 

其中(:ID => IDS)将使用在生成查询()。然后排序!方法会遍历查询结果,并在IDS阵列比较编号的位置。

Suppose I have a non-empty array ids of Thing object ids and I want to find the corresponding objects using things = Thing.find_all_by_id(ids). My impression is that things will not necessarily have an ordering analogous to that of ids.

  1. Is my impression correct?

  2. If so, what can I used instead of find_all_by_id that preserves order and doesn't hit the database unnecessarily many times?

解决方案

  1. Yes
  2. Use Array#sort

Check it out:

Thing.where(:id => ids).sort! {|a, b| ids.index(a.id) <=> ids.index(b.id)}

where(:id => ids) will generate a query using an IN(). Then the sort! method will iterate through the query results and compare the positions of the id's in the ids array.

这篇关于是否ActiveRecord的find_all_by_X preserve订单?如果没有,应该用什么呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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