Martijn Kerckhaert Martijn Kerckhaert - 2 months ago 14
Ruby Question

Sorting query in 2 groups

I have Users that have a state: "inactive" or "active"
I need to sort them on "created_at" in 2 batches "inactive" and "active"

Result would be as following: First all active users sorted on creation date and then all inactive users sorted on creation date.

Result would be:

User 1 - 1/5/17 - active
User 2 - 1/3//17 - active
User 3 - 1/1//17 - active
User 4 - 1/7/17 - inactive
User 5 - 1/4/17 - inactive

I could potentially just just get 2 arrays and sort those based on creation date but it would be nice to do it in 1 go.


Try like this:

User.order(state: :asc, created_at: :desc)

To get the columns you want:

User.order(state: :asc, created_at: :desc).pluck(:name, :created_at, :state)

To get the exact output:

User.order(state: :asc, created_at: :desc).pluck(:name, :created_at, :state).map{|u| u.join(" - ")}