我收到按“收入”排序的 UserId 列表(一次大约 1000 个)。我在“我的系统的数据库”中有用户记录,但“收入”列不存在。我想从“我的系统数据库”中检索用户 在列表中收到的排序顺序中。我尝试使用 Active Record 执行以下操作,希望记录的检索顺序与排序列表中的顺序相同,但它不起作用。
//PSEUDO CODE
User.all(:conditions => {:id => [SORTED LIST]})
我在下面的链接中找到了类似问题的答案,但不确定如何使用 Active Record 实现建议的解决方案。
还有其他方法吗?
请指导。
沙都。
最佳答案
您的答案链接提供了您所需要的,您只需要以灵活的方式在 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_name
和 self
它没有用任何特定的实现类名。
关于ruby-on-rails - 使用 Rails Active Record 的 IN 列表中的 Postgres ORDER BY 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12012574/