【问题标题】:Rails Sorting the record based on the array passed in where conditionRails根据where条件传入的数组对记录进行排序
【发布时间】:2015-06-26 07:27:59
【问题描述】:

我想按照我在数组中传递值的顺序对 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]

我该怎么做。

【问题讨论】:

  • 想要按我将它传递到数组中的顺序而不是按 id 对其进行排序

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


【解决方案1】:

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

在 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 的数组

【讨论】:

    【解决方案2】:

    使用 ids 数组的索引进行简单排序:

    products = Product.where(id: ids).sort_by { |prod| ids.index(prod.id) }
    

    此外,它与数据库无关,在 Ruby 中也可以这样做,因为无论如何您都不会拥有数百万个 id。

    【讨论】:

    • 其实这会返回一个数组不活跃的记录关系。
    【解决方案3】:

    答案仅适用于 mysql

    mysql中有一个函数叫FIELD()

    所以你可以做类似的事情

    products = Product.where(id: ids).order("field(id, #{ids.join ','})")
    

    【讨论】:

    • 我实际上正在寻找 postgress 。有什么方法可以实现与 postgress 相同的机智。
    【解决方案4】:

    在 Postgres 中

    hot_offer_ids = ["7081", "7083", "6917", "5075"]
    values = ''
    hot_offer_ids.each_with_index do |offer_id, index|
      values += ", " if index > 0
      values += %((#{offer_id}, #{index}))
    end
    hot_offers = Offer.joins("join (VALUES #{values}) as x(id, ordering) on offers.id = x.id").order("x.ordering")
    

    【讨论】:

      【解决方案5】:

      您可以使用这个 gem (order_as_specified),它允许您像这样进行本机 SQL 排序:

      Model.where(id: ids).order_as_specified(id: ids)
      

      参考答案:Link

      【讨论】:

        猜你喜欢
        • 2014-09-21
        • 2013-09-30
        • 2011-04-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-01
        • 1970-01-01
        相关资源
        最近更新 更多