ruby-on-rails - 使用 Rails Active Record 的 IN 列表中的 Postgres ORDER BY 值

标签 ruby-on-rails postgresql activerecord sql-order-by in-clause

我收到按“收入”排序的 UserId 列表(一次大约 1000 个)。我在“我的系统的数据库”中有用户记录,但“收入”列不存在。我想从“我的系统数据库”中检索用户 在列表中收到的排序顺序中。我尝试使用 Active Record 执行以下操作,希望记录的检索顺序与排序列表中的顺序相同,但它不起作用。

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

我在下面的链接中找到了类似问题的答案,但不确定如何使用 Active Record 实现建议的解决方案。

ORDER BY the IN value list

还有其他方法吗?

请指导。

沙都。

最佳答案

您的答案链接提供了您所需要的,您只需要以灵活的方式在 Ruby 中对其进行编码。

像这样:

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

事实上,您可以轻松地将其放入模块中,并将其混合到任何需要它的 ActiveRecord 类中,因为它使用 table_nameself 它没有用任何特定的实现类名。

关于ruby-on-rails - 使用 Rails Active Record 的 IN 列表中的 Postgres ORDER BY 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12012574/

相关文章:

postgresql - PL/pgSQL : accessing fields of an element of an array of custom type

ruby-on-rails - rails 中 postgresql 数据库中的 camelCase 列(ActiveRecord)

ruby-on-rails - 如何在 Postgresql 中连接两个字段

ruby-on-rails - Rails,重复代码重构

ruby-on-rails - Rails 以单数形式命名 Controller 有什么缺点?

ruby-on-rails - 无法在 Linux Mint 中安装 curb gem

sql - 如何选择表格中前 95% 的行

javascript - pipe() 数据到 Json 文件或到 PostgreSQL

sql - Rails3:具有散列替换(如.where())的SQL执行

ruby-on-rails - Ruby on Rails 教程 - 第 9 章 : Missing template update