Assuming Model.pluck(:id)
returns [1,2,3,4]
and you want the order of [2,4,1,3]
The concept is to to utilize the ORDER BY CASE WHEN
SQL clause. For example:
SELECT * FROM colors
ORDER BY
CASE
WHEN code='blue' THEN 1
WHEN code='yellow' THEN 2
WHEN code='green' THEN 3
WHEN code='red' THEN 4
ELSE 5
END, name;
In Rails, you can achieve this by having a public method in your model to construct a similar structure:
def self.order_by_ids(ids)
if ids.present?
order_by = ["CASE"]
ids.each_with_index do |id, index|
order_by << "WHEN id='#{id}' THEN #{index}"
end
order_by << "END"
order(order_by.join(" "))
end
else
all # If no ids, just return all
end
Then do:
ordered_by_ids = [2,4,1,3]
results = Model.where(id: ordered_by_ids).order_by_ids(ordered_by_ids)
results.class # Model::ActiveRecord_Relation < ActiveRecord::Relation
The good thing about this. Results are returned as ActiveRecord Relations (allowing you to use methods like last
, count
, where
, pluck
, etc)