如何在Rails中对给定字段中的给定值进行排序和返回记录?

时间:2015-06-03 18:43:19

标签: sql ruby-on-rails postgresql ruby-on-rails-4

class Foo < ActiveRecord::Base
end

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

如何订购,以便最后返回状态为Foos的所有on_hold

RoR 4. Postgres。

1 个答案:

答案 0 :(得分:2)

它会起作用:

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

对Postgresql 布尔排序的快速测试:

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=#

正如 @muistooshort 所说,你可以这样做:

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