简体   繁体   English

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

[英]Rails Sorting the record based on the array passed in where condition

I want to sort my where condition result in the order i am passing the values in array .我想按照我在 array 中传递值的顺序对我的 where 条件结果进行排序。 what i am doing is i have an array of ids我正在做的是我有一个 id 数组

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

When i am passing this array to where condition like :当我将此数组传递给 where 条件时,例如:

products = Product.where(id: ids)

its returning the result active record relation in different order (random order)something like :它以不同的顺序(随机顺序)返回结果活动记录关系,例如:

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

(this is active record relation object i have mention only ids here ) (这是活动记录关系对象,我在这里只提到了 id)

But i want it to return the object in same order i am passing the the values like (In active record relation object not an array)但我希望它以相同的顺序返回对象,我正在传递类似的值(在活动记录关系对象中,而不是数组中)

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

How can i do this .我怎样才能做到这一点 。

I have got the solution of this just need to do我有这个只需要做的解决方案

In product model inside product.rb file put :在 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

And query will be :查询将是:

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

Here ids will be array of id's这里 ids 将是 id 的数组

Simply sort by using indices of your ids array:只需使用 ids 数组的索引进行排序:

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

Plus it's database agnostic, and it's ok to do in Ruby as you won't have millions of ids in any case.此外,它与数据库无关,而且可以在 Ruby 中进行,因为在任何情况下都不会有数百万个 ID。

The answer is for mysql only答案仅适用于 mysql

There is a function in mysql called FIELD() mysql 中有一个函数叫FIELD()

So you can do something like所以你可以做类似的事情

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

In Postgres在 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")

You can use this gem ( order_as_specified ) that allows you to do native SQL ordering like this:您可以使用这个 gem ( order_as_specified ),它允许您像这样执行本机 SQL 排序:

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

Reference Answer : Link参考答案: 链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM