2

so I have the following query for my companies companies.where(industry: industries_queried)

I would like to sort them, so that the first records returned are the ones with plan_id == 3, then 2, then 1. (descendingly)

But then, I would also like to arrange each of these 4 parts, so that they are sorted alphabetically per name.

How would I go about doing this in Rails 5?

0

1 Answer 1

3

The Active Record Query Interface guide, gives us the following info on ordering records.

4 Ordering

To retrieve records from the database in a specific order, you can use the order method.

For example, if you're getting a set of records and want to order them in ascending order by the created_at field in your table:

Customer.order(:created_at)
# OR
Customer.order("created_at")

You could specify ASC or DESC as well:

Customer.order(created_at: :desc)
# OR
Customer.order(created_at: :asc)
# OR
Customer.order("created_at DESC")
# OR
Customer.order("created_at ASC")

Or ordering by multiple fields:

Customer.order(orders_count: :asc, created_at: :desc)
# OR
Customer.order(:orders_count, created_at: :desc)
# OR
Customer.order("orders_count ASC, created_at DESC")
# OR
Customer.order("orders_count ASC", "created_at DESC")

Applying this to your issue you would end up with:

companies.where(industry: industries_queried).order(plan_id: :desc, name: :asc)
Sign up to request clarification or add additional context in comments.

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.