Ruby on Rails:有没有办法从数据库中提取项目并按指定顺序返回它们? [英] Ruby on Rails: Is there any way to pull items from the database and have them returned in a specified order?

查看:14
本文介绍了Ruby on Rails:有没有办法从数据库中提取项目并按指定顺序返回它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组物品 ID,item_ids.

I have an array of item ID's, item_ids.

我将此数组传递给 ActiveRecord 查询以从数据库中检索相应的项目:Item.where(:id => item_ids)

I'm passing this array into an ActiveRecord query to retrieve the corresponding items from the database: Item.where(:id => item_ids)

有什么方法可以让返回的项目按照通过 item_ids 数组传入的顺序返回?

Is there any way to get the items returned in the same order as passed in via the item_ids array?

如果有什么不同,我使用 Ruby on Rails 3.0.12,将 PostgreSQL 作为我的数据库.

If it makes a difference, I'm on Ruby on Rails 3.0.12 with PostgreSQL as my database.

推荐答案

可以让数据库做排序,避免多个index 调用,您只需要记住 SQL ORDER BY 由 表达式 排序,而不是:

You can get the database to do the sorting and avoid multiple index calls, you just have to remember that an SQL ORDER BY orders by an expression, not a column:

whens = item_ids.collect.with_index { |id, i| "when #{id} then #{i}" }.join(' ')
items = Item.where(:id => item_ids).order("case id #{whens} end")

这篇关于Ruby on Rails:有没有办法从数据库中提取项目并按指定顺序返回它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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