Postgres ORDER BY values in IN list using Rails Active Record

橙三吉。 提交于 2019-12-22 12:19:15

问题


I receive a list of UserIds(about 1000 at a time) sorted by 'Income'. I have User records in "my system's database" but the 'Income' column is not there. I want to retrieve the Users from "my system's database" in the Sorted Order as received in the list. I tried doing the following using Active Record expecting that the records would be retrieved in the same order as in the Sorted List but it does not work.

//PSEUDO CODE
User.all(:conditions => {:id => [SORTED LIST]})

I found an answer to a similar question at the link below, but am not sure how to implement the suggested solution using Active Record.

ORDER BY the IN value list

Is there any other way to do it?

Please guide.

Shardul.


回答1:


Your linked to answer provides exactly what you need, you just need to code it in Ruby in a flexible manner.

Something like this:

class User
  def self.find_as_sorted(ids)
    values = []
    ids.each_with_index do |id, index|
      values << "(#{id}, #{index + 1})"
    end
    relation = self.joins("JOIN (VALUES #{values.join(",")}) as x (id, ordering) ON #{table_name}.id = x.id")
    relation = relation.order('x.ordering')
    relation
  end
end

In fact you could easily put that in a module and mixin it into any ActiveRecord classes that need it, since it uses table_name and self its not implemented with any specific class names.




回答2:


MySQL users can do this via the FIELD function but Postgres lacks it. However this questions has work arounds: Simulating MySQL's ORDER BY FIELD() in Postgresql



来源:https://stackoverflow.com/questions/12012574/postgres-order-by-values-in-in-list-using-rails-active-record

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!