I need to find the records in the exact order as it is passed in as the search parameter.
For example, I have a string :
item_list = "23,12,54,45"
With the following query, I get records in the asc order of 'item_list' - "12,23,45,54".
Inventory.find(item_list.split(","))
How do I modify above query such that it returns the records in the same order of 'item_list'.
Thanks.
Try this, though it may only work in MySQL:
Inventory.where("id IN (#{item_list})").order("find_in_set(id, '#{item_list}')")
For smaller datasets you could let Ruby sort the results, but I think letting the database do the work for you is best for larger sets.
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