<分区>
我有一个项目 ID 数组,item_ids
。
我将此数组传递到 ActiveRecord 查询中以从数据库中检索相应的项目:Item.where(:id => item_ids)
有什么方法可以让返回的项目与通过 item_ids
数组传入的顺序相同?
如果它有所作为,我正在使用 Ruby on Rails 3.0.12 和 PostgreSQL 作为我的数据库。
<分区>
我有一个项目 ID 数组,item_ids
。
我将此数组传递到 ActiveRecord 查询中以从数据库中检索相应的项目:Item.where(:id => item_ids)
有什么方法可以让返回的项目与通过 item_ids
数组传入的顺序相同?
如果它有所作为,我正在使用 Ruby on Rails 3.0.12 和 PostgreSQL 作为我的数据库。
最佳答案
可以让数据库做排序,避免出现多个index
调用,您只需要记住 SQL ORDER BY 按表达式而不是列排序:
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 - ruby rails : Is there any way to pull items from the database and have them returned in a specified order?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12502222/