活动记录按ID排序
如果我有id的记录:1,2,3,4并且想要以某种方式对它们进行排序,比如1,4,4,3,我该怎么办呢?
我认为这样的事情,但它当然不起作用。
Service.all.order(id: [1, 4, 2, 3])
就在两天前,Justin Weiss写了一篇关于这个问题的博客文章 。
这似乎是告诉数据库有关首选顺序并直接从数据库加载按该顺序排序的所有记录的好方法。 他博客文章的例子。
将以下扩展名添加到您的应用程序:
# eg in config/initializers/find_by_ordered_ids.rb module FindByOrderedIdsActiveRecordExtension extend ActiveSupport::Concern module ClassMethods def find_ordered(ids) order_clause = "CASE id " ids.each_with_index do |id, index| order_clause << "WHEN #{id} THEN #{index} " end order_clause << "ELSE #{ids.length} END" where(id: ids).order(order_clause) end end end ActiveRecord::Base.include(FindByOrderedIdsActiveRecordExtension)
这将允许您编写这样的查询:
Service.find_ordered([2, 1, 3]) # => [2, 1, 3]
order = [1,4,2,3] @services = [] order.each do |id| @services << Services.find(id) end