ruby-on-rails - ruby rails : Is there any way to pull items from the database and have them returned in a specified order?

标签 ruby-on-rails postgresql activerecord rails-activerecord

<分区>

我有一个项目 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/

相关文章:

ruby-on-rails - 使用Docker-compose进行卷挂载的问题

mysql - 使 GROUP_CONCAT 查询更高效

ruby-on-rails - Jasmine Rice on Rails 4

sql - 计算除第一行以外的列的平均值

postgresql - 如何在 PostgreSQL 中使用 Knex.js 执行级联删除?

mysql - 如何关联已连接表中的记录? - ruby on Rails

ruby-on-rails - Rails 命令只能在一个终端上运行

postgresql - Postgres 数据库中特殊的时区处理

ruby - Ruby Activerecord 中的组合更新

ruby-on-rails - 按 parent 和 child 的 created_at 排序的最佳方式是什么?