Ruby on Rails: search for records without sorting

I need to find the records in the exact order as it is passed as a search parameter.

For example, I have a line:

item_list = "23,12,54,45"

With the following query, I get entries in ascending order "item_list" - "12,23,45,54".

Inventory.find(item_list.split(","))

How can I change the above request so that it returns entries in the same order as "item_list".

Thank.

+5
source share
4 answers

Try this, although it can only work in MySQL:

Inventory.where("id IN (#{item_list})").order("find_in_set(id, '#{item_list}')")

For smaller datasets, you can let Ruby sort the results, but I think letting the database work for you is best for large datasets.

+4

:

ids   = item_list.split(',')
items = Inventory.find(ids).sort_by { |i| ids.index(i.id) }

, sort_by , . , , , sort_by.

, , , :

>> a = [ 23, 11, 42, 5 ]
>> b = [5, 23, 11, 42]
>> b.sort_by { |i| a.index(i) }
=> [23, 11, 42, 5]
+1
item_list.split(",").collect do |item|
  Inventory.find(item)
end
0
source
 unordered_records = Inventory.where(:id => item_list)
 item_list.collect { |id| unordered_records.detect { |x| x.id == id } }
0
source

All Articles