Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: Find records without Sorting

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.

like image 411
safalmj Avatar asked Aug 23 '11 06:08

safalmj


1 Answers

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.

like image 184
Dex Avatar answered Oct 14 '22 16:10

Dex