ruby-on-rails - Rails 根据传入where条件的数组对记录进行排序

标签 ruby-on-rails arrays ruby ruby-on-rails-4 rubygems

我想按照传递数组中值的顺序对 where 条件结果进行排序。我正在做的是我有一个 id 数组

ids = [80, 20, 3, 91, 84, 90, 98, 97, 68, 99, 92, 73]

当我将这个数组传递给 where 条件时:

products = Product.where(id: ids)

它以不同的顺序(随机顺序)返回结果事件记录关系,例如:

=>[ 20 ,84, 3,98 , .............. ] 

(这是事件记录关系对象,我在这里只提到了 id)

但我希望它以与传递值相同的顺序返回对象(在事件记录关系对象中不是数组)

=> [80, 20, 3, 91, 84, 90, 98, 97, 68, 99, 92, 73]

我该怎么做。

最佳答案

我已经得到了这个只需要做的解决方案

在 product.rb 文件中的产品模型中放置:

 def self.order_by_ids(ids)
    order_by = ["case"]
    ids.each_with_index.map do |id, index|
      order_by << "WHEN id='#{id}' THEN #{index}"
    end
    order_by << "end"
    order(order_by.join(" "))
  end

查询将是:

products = Product.where(:id => ids).order_by_ids(ids)

这里的 ids 将是 id 的数组

关于ruby-on-rails - Rails 根据传入where条件的数组对记录进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31067428/

相关文章:

jquery - 使用 jquery 更新 html 表格行

javascript - 在 json_decode 中获取 null

javascript - 尽管进行了检查,但访问 javascript 数组元素时出错

ruby-on-rails - ROR 相当于 Phoenix Mix?

ruby - 获取当月第一天的最有效方法是什么?

javascript - 带有嵌入式 API key 的静态 API 文档

ruby-on-rails - 将自定义字段动态添加到模型中

ruby-on-rails - 如何在 rails 中有两个不同的注册页面(使用设计)

ruby-on-rails - 使用 Activemerchant Gem 切换到多个商家帐户以进行 Paypal 快速结账

python - 从 CSV 文件读取时对数组的数值运算