Ruby on Rails的:有没有办法拉从数据库项目,并让他们在指定的顺序返回? [英] Ruby on Rails: Is there any way to pull items from the database and have them returned in a specified order?
问题描述
我有项目编号的数组, 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.
推荐答案
您可以得到数据库来进行排序,并避免多次的 首页
电话,你只需要记住一个SQL ORDER BY订单由 EX pression 的,不是的列的:
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屋!