Home > Enterprise >  Rails custom alphabetical sort
Rails custom alphabetical sort

Time:10-13

I wanted to sort the query alphabetically, but in a custom order

User
  .includes(:teachers)
  .sort_by(&:location)

Location is a code example A, B, C, D

But I want to sort location in A, D, C, B.

CodePudding user response:

If your sort order is arbitrary like in your example (A, D, C, B), you'll have to define it somewhere.

LOCATION_ORDER = {
  'A' => 0,
  'D' => 1,
  'C' => 2,
  'B' => 3,
}

Then, you can sort by that.

User
  .includes(:teachers)
  .sort_by { |u| LOCATION_ORDER[u.location] }

It's worth noting that sort_by will perform the sort in your Ruby application, not the database, but since you're using sort_by already, I'll assume that's OK with you.

CodePudding user response:

Ruby on Rails 7.0 introduced the ActiveRecord::QueryMethods#in_order_of method that allows doing these kinds of custom ordering in the database like this:

User
  .includes(:teachers)
  .in_order_of(location: [A, D, C, B])

The [A, D, C, B] array has to be replaced with useful objects, for example, a list of location names when the location attribute has the datatype string.

  • Related