简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM