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?

1
  • 1
    I doubt it, you'll probably have to use a bit of custom SQL with this: stackoverflow.com/a/9475755/2076787 or MySQL's FIELD. Commented Dec 3, 2014 at 16:13

1 Answer 1

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')")
Sign up to request clarification or add additional context in comments.

1 Comment

(Assuming the color column is called color)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.