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.

3
  • 1
    And Rails Active query order by multiple values in specific order? and Sort list of objects according to an array (Rails) and probably dozens more. Of course, it is easier to find the duplicates when you know what answer to search for. Commented Nov 20, 2018 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) Commented Nov 21, 2018 at 6:31
  • For any database type, hash = @items.group_by(&:id); @items = @item_order.map(&hash.method(:[])).flatten Commented Nov 21, 2018 at 11:44

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.