0

If I have an array such as: ['Apple','Orange','Pear']

How could I retrieve records from a model by implementing a "custom sort"? For example, what if I want to sort the fruit_type column by Orange, Pear, and then Apple?

Not trying to sort alphabetically or numerically, but just based on a custom order that I'm looking for.

halfer
  • 19,824
  • 17
  • 99
  • 186
LewlSauce
  • 5,326
  • 8
  • 44
  • 91
  • You have a two options, 1. Custom indexing(position) like `Eyeslandic` mentioned, or 2. Custom algorithm )) – 7urkm3n Aug 05 '19 at 15:10

1 Answers1

0

The best way I think would be to create a new table with something like

create_table :fruit_types do |t|
  t.string  :name
  t.integer :sort_order
  # .....
end

Then use that in your model

# model.rb
belongs_to :fruit_type

Then query with

Model.joins(:fruit_type).order('fruit_types.sort_order')
Eyeslandic
  • 14,553
  • 13
  • 41
  • 54