John
John

Reputation: 1323

How sorting works in ruby on rails? when there are multiple fields to sort in a single query

I have a model with the fields price, min_price,max_price, discount,in my product table. if I want to execute ascending descending orders, how that will get executed when we apply for an order on multiple fields. for example like below.

@products = Product.order("price asc").order("min_price desc").order("max_price asc").order("updated_at asc") (Query might be wrong but for reference im adding)

will it order as per the order sequence ?

Upvotes: 0

Views: 146

Answers (1)

David Aldridge
David Aldridge

Reputation: 52376

If you append .to_sql to that, it will show the generated SQL so you can investigate yourself.

I tried a similar query:

Book.select(:id).order("id asc").order("pub_date desc").to_sql
=> "SELECT \"books\".\"id\" FROM \"books\" ORDER BY id asc, pub_date desc"

You might instead:

Book.select(:id).order(id: :asc, pub_date: :desc).to_sql
=> "SELECT \"books\".\"id\" FROM \"books\" ORDER BY \"books\".\"id\" ASC, \"books\".\"pub_date\" DESC"

... which you see adds the table name in, so is more reliable when if you are accessing multiple tables

Upvotes: 2

Related Questions