Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lightweight method to order on boolean attribute in true/false/nil order

Is there a lightweight way of doing something like this?

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

The following aren't what I want:

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

Foo.order("bar DESC").map{|f| f.bar}.uniq
=> [nil, true, false]
like image 642
steven_noble Avatar asked Oct 18 '25 23:10

steven_noble


1 Answers

Found the answer:

Foo.order("bar DESC NULLS LAST").map{|f| f.bar}.uniq
=> [true, false, nil]
Foo.order("bar DESC NULLS LAST").class
=> Foo::ActiveRecord_Relation
like image 107
steven_noble Avatar answered Oct 20 '25 11:10

steven_noble



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!