以 true/false/nil 顺序对布尔属性进行排序的轻量级方法

ste*_*ble 4 sql activerecord ruby-on-rails

有没有一种轻量级的方法来做这样的事情?

Foo.order(:bar => [true, false, nil]).map{|f| f.bar}.uniq
=> [true, false, nil]
Foo.order(:bar => [true, false, nil]).class
=> Foo::ActiveRecord_Relation
Run Code Online (Sandbox Code Playgroud)

以下不是我想要的:

Foo.order(:bar).map{|f| f.bar}.uniq
=> [false, true, nil]

Foo.order("bar DESC").map{|f| f.bar}.uniq
=> [nil, true, false]
Run Code Online (Sandbox Code Playgroud)

ste*_*ble 5

找到了答案:

Foo.order("bar DESC NULLS LAST").map{|f| f.bar}.uniq
=> [true, false, nil]
Foo.order("bar DESC NULLS LAST").class
=> Foo::ActiveRecord_Relation
Run Code Online (Sandbox Code Playgroud)