I want te get, for example, products by id array but I want these products on same order that id array.
For example, I want products with id 6, 3, 8:
ids = [6, 3, 8]
Product.where(id: ids)
It gives me products but the first is product with id = 3, second with id = 6...
And I want these products in same order that ids array. I want the first product with id = 6, the second with id = 3...
How could I do that in Products query?
Indexing should work:
Product.where(id: ids).index_by(&:id).values_at(*ids)
Or just (checked in MySQL, but sanitize ids before if ids are coming from external source):
Product.where(id: ids).order("field(id, #{ids.join(', ')})")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With