MechDog
MechDog

Reputation: 548

Sort a rails query based on array order

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?

Upvotes: 1

Views: 725

Answers (1)

kddeisz
kddeisz

Reputation: 5182

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

@fruit = Fruit.where(seeds: true).order("FIELD(color, 'Red', 'Blue', 'Yellow')")

Upvotes: 3

Related Questions