活动记录按ID排序

时间:2015-04-22 00:25:48

标签: ruby-on-rails ruby sorting ruby-on-rails-4

如果我有id的记录:1,2,3,4并且想要以某种方式对它们进行排序,比如1,4,4,3,我该怎么办呢?

我认为是这样的,但它当然不起作用。

Service.all.order(id: [1, 4, 2, 3])

2 个答案:

答案 0 :(得分:2)

Justin Weiss两天前写了blog article about this problem

这似乎是一种很好的方法来告诉数据库有关首选顺序并直接从数据库加载按该顺序排序的所有记录。他的blog article

示例

将以下扩展名添加到您的应用程序中:

# e.g. 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]

答案 1 :(得分:0)

 order = [1,4,2,3]
 @services = []
   order.each do |id|
   @services << Services.find(id)
   end