rigyt
rigyt

Reputation: 2353

Order by date then id, not ordering by second column

I'm ordering an Active Record relation by a date column then an foreign key id column, but the second ordering doesn't take effect.

recs.order('date, parent_id')
recs.order('date asc, parent_id asc')
etc.

None of the expected ordering works when the first column is a date. It simply won't order the second column within date.

This orders by the date column but NOT by the parent_id column, eg:

01/01/2015 ParentB
01/01/2015 ParentB
01/01/2015 ParentA
01/01/2015 ParentB
20/06/2015 ParentA
...

You see the records are not ordered by parent_id with a date. Using Rails 4.2.3, Postgres 9. The date attribute is defined as date type in the migration, so shouldn't have a time portion. The ordering should be:

01/01/2015 ParentA
01/01/2015 ParentB
01/01/2015 ParentB
01/01/2015 ParentB
20/06/2015 ParentA
...

(assuming ParentA is displaying for parent_id 1 and ParentB for parent_id 2)

Upvotes: 3

Views: 1329

Answers (1)

Mihai Dinculescu
Mihai Dinculescu

Reputation: 20033

In Rails 4, you can do it like this

Model.order(column1: :asc, column2: :desc)

More from Rails Guides

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

If you want to call order multiple times e.g. in different context, new order will append previous one

Client.order("orders_count ASC").order("created_at DESC")  
# SELECT * FROM clients ORDER BY orders_count ASC, created_at DESC

Upvotes: 2

Related Questions