When you attempt to sort items in rails, any nils automatically come first - they're considered to have a lower "value" than anything that's not nil.
Now, on many occasions, you'll want to ensure that nils go at the end - as was the case with the thing we were working on - so there are a couple of options: one obvious, one much less so.
Sort by "property" in ascending order:
:order => 'property is nil ASC, property ASC'
The above two examples shift any nils to the end of the list in the first part of the sort as "property is nil" resolves as 0 for non-nils and 1 for nils. You can then order by that property as normal.
Alternatively, you could do the following to sort in ascending order:
:order => '-property DESC'
Notice that there is a minus sign in front of the property, which effectively reverses the order the items would be listed in. The minus sign has no effect on nils so when we then sort in descending order (notice that the ASC has become a DESC), we get the non-nil items back in the original order (we reverse the reverse) and the nils at the end as we would expect from a DESC.
Just thought I'd share that with you as it had us scratching our heads for a wee while.
This saved my ass, thanks.
ReplyDelete