0

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.

1
  • 2
    It is entiely unclear what kind of an order "A, D, C, B" is. The question is unanswerable without more details, preferably with some real (or at least realistic) sample data. Commented Oct 13, 2022 at 3:16

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is a nice addition. Those using rails < 7.0 the underlying implementation is fairly straight forward so it shouldn't be hard to build out a functional equivalent. MySql has its own more efficient solution as well due to the fact that MySQL has this function built in.
1

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.

Comments

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.