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.

1
  • You have a two options, 1. Custom indexing(position) like Eyeslandic mentioned, or 2. Custom algorithm )) Commented Aug 5, 2019 at 15:10

1 Answer 1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.