0

I have 11 items in an array that have and ID of 1 to 11.

Instead of just showing them in the default order, I want to manually customize the order using another array.

@items = Item.all # only 11 items in item table
@item_order = [4,9,8,7,3,2,1,10,11,5,6]

@items.sort_by_id ?

Is something like this possible? Currently everything I have tried hasn't worked.

Kobius
  • 674
  • 7
  • 28
  • 1
    And [**Rails Active query order by multiple values in specific order?**](https://stackoverflow.com/q/19173020/479863) and [**Sort list of objects according to an array (Rails)**](https://stackoverflow.com/q/41419169/479863) and probably dozens more. Of course, it is easier to find the duplicates when you know what *answer* to search for. – mu is too short Nov 20 '18 at 21:16
  • Appreciate the help. For anyone reading - I would suggest using this method: b = [5,3,1] Country.where(id: b).index_by(&:id).values_at(*b) – Kobius Nov 21 '18 at 06:31
  • For any database type, `hash = @items.group_by(&:id); @items = @item_order.map(&hash.method(:[])).flatten` – ray Nov 21 '18 at 11:44

0 Answers0