1

I want to sort an ActiveRecord query based on the values in an array. Something like:

@fruits=Fruit.where(seeds: true)._________________________

Say I wanted to sort the results by color using the array ['Red','Blue','Yellow']

I see where SQL supports the use of a case statement for custom ordering, does Rails have something that utilizes this?

Holger Just
  • 52,918
  • 14
  • 115
  • 123
MechDog
  • 508
  • 7
  • 18
  • 1
    I doubt it, you'll probably have to use a bit of custom SQL with this: http://stackoverflow.com/a/9475755/2076787 or MySQL's `FIELD`. – D-side Dec 03 '14 at 16:13

1 Answers1

3

If you're using MySQL, you can use FIELD. It would look like:

@fruit = Fruit.where(seeds: true).order("FIELD(color, 'Red', 'Blue', 'Yellow')")
kddeisz
  • 5,162
  • 3
  • 21
  • 44