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])
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]
order = [1,4,2,3]
@services = []
order.each do |id|
@services << Services.find(id)
end