3

I have an array of item ID's, item_ids.

I'm passing this array into an ActiveRecord query to retrieve the corresponding items from the database: Item.where(:id => item_ids)

Is there any way to get the items returned in the same order as passed in via the item_ids array?

If it makes a difference, I'm on Ruby on Rails 3.0.12 with PostgreSQL as my database.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
Mike Liu
  • 149
  • 10

1 Answers1

4

You can get the database to do the sorting and avoid multiple index calls, you just have to remember that an SQL ORDER BY orders by an expression, not a column:

whens = item_ids.collect.with_index { |id, i| "when #{id} then #{i}" }.join(' ')
items = Item.where(:id => item_ids).order("case id #{whens} end")
mu is too short
  • 426,620
  • 70
  • 833
  • 800