Search code examples
ruby-on-railsrubyruby-on-rails-5

Sorting record array twice while maintaining initial sort


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?


Solution

  • 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)