有效记录按ID排序 [英] Active Records order by ids
本文介绍了有效记录按ID排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有ID为:1、2、3、4的记录,并且想要以某种方式对它们进行排序,例如1、4、2、3,我该怎么做?
If I have records with ids: 1,2,3,4 and want sort them a certain way, like this 1, 4, 2, 3, how can I do this?
我认为是这样,但这当然不起作用.
I think something like that, but it doesn't work of course.
Service.all.order(id: [1, 4, 2, 3])
推荐答案
Justin Weiss wrote a blog article about this problem just two days ago.
告诉数据库有关首选顺序并直接从数据库中加载按该顺序排序的所有记录似乎是一个好方法.他的博客文章.
It seems to be a good approach to tell the database about the preferred order and load all records sorted in that order directly from the database. Example from his blog article.
在您的应用程序中添加以下扩展名:
Add the following extension to your application:
# 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)
这将使您可以编写如下查询:
That would allow you to write queries like this:
Service.find_ordered([2, 1, 3]) # => [2, 1, 3]
这篇关于有效记录按ID排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文