B Seven
B Seven

Reputation: 45943

How to sort and return records with a given value in a given field last in Rails?

class Foo < ActiveRecord::Base
end

Foo.order( status: :on_hold ...?

How to order so that all Foos with a status of on_hold are returned last?

RoR 4. Postgres.

Upvotes: 1

Views: 71

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118271

It will work :

Foo.order( "status = 'on_hold', status")

A quick test on Postgresql Boolean ordering :

app=# select * from test1;
 a |    b
---+---------
 t | sic est
 f | non est
(2 rows)

app=# select * from test1 order by a;
 a |    b
---+---------
 f | non est
 t | sic est
(2 rows)

app=#

Well as @muistooshort said, you can do :

Foo.order("CASE status WHEN 'on_hold' THEN 1 ELSE 0 END, status")

Upvotes: 2

Related Questions