I have ids array ids = [5,2,1,6]
.
I'd like to find all records with these ids and keep the same order as in the ids
array.
Regular records = Product.find(ids)
does not keep this order(not sure, but probably it sorts by id).
I have ids array ids = [5,2,1,6]
.
I'd like to find all records with these ids and keep the same order as in the ids
array.
Regular records = Product.find(ids)
does not keep this order(not sure, but probably it sorts by id).
Try this:
ids = [5,2,1,6]
records = Product.find(ids).index_by(&:id).values_at(*ids)
The best way to do this is using a CASE statement (Postgres).
def order_by_id(ids)
order_by = ["case"]
ids.each_with_index.map do |id, index|
order_by << "WHEN id=#{ActiveRecord::Base.connection.quote id} THEN #{index}"
end
order_by << "end"
order(order_by.join(" "))
end
That should get you most of the way there.
This will match each id to a product
ids.map{ |id| Product.find(id) }