为了ActiveRecord的外部阵列 [英] ActiveRecord order by external array

查看:108
本文介绍了为了ActiveRecord的外部阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

予有ID的数组,存储在某种外部存储(轨道缓存或redis的)。在控制器的行动我使用它,即获取这些数据,然后选择对象

I have an array of ids, stored in some external storage (rails cache or redis). In controller's action I fetch this data and select object using it, i.e.

ids = [5, 1, 17, 84] # really fetched from external source
result = MyModel.where(:id => ids)

我也希望它被命令只是相同array_of IDS入侵检测系统:

I also want it to be ordered just the same as ids in array_of ids:

ids == result.map(&:id) # => true

作为解决方法我使用随MySQL场函数排序:

As workaround I use sorting by mysql FIELD function:

MyModel.where(:id => ids).order("FIELD(id, #{ids.join ', '})")

不过,我不喜欢这种方式,因为它是MySQL的具体情况下的大 IDS 阵列创建很长的查询。 有没有更好的,数据库无关的方式做到这一点?从数据库获取未排序的数据和红宝石端排序是不可取的,因为它的资源价格昂贵,很难与分页使用。

But I don't like this approach as it is mysql specific and creates very long queries in case of big ids array. Is there better, DB-agnostic way to do it? Fetching unsorted data from DB and sorting on ruby side is undesirable because it's resource-expensive and hard to use with pagination.

感谢。

推荐答案

如果你不介意接收阵列,而不是一个ActiveRecord集合,你可以使用:

If you don't mind receiving an array instead of an ActiveRecord Collection, you can use:

result = MyModel.find(ids).sort_by {|m| ids.index(m.id)}

这篇关于为了ActiveRecord的外部阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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