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

时间:2015-07-31 02:24:45

标签: sql ruby-on-rails activerecord

是否采用轻量级方式做这样的事情?

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

以下不是我想要的:

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

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

2 个答案:

答案 0 :(得分:1)

找到答案:

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

答案 1 :(得分:0)

这对我很有用:

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

我正在使用ruby 2.1.5,rails 4.1.12。

相关问题