Follow Along as I Stumble on the Path to Learning RoR

Sorting Nil Results to End when Order Ascending (ASC)

I had to sort a bunch of records with order ascending, but the problem is that some of these records will occasionally be nil.   For my use case, I needed the nils to be listed at the end, with the non-nils sorted in ascending order.

So I had something like this:

@bars = @foo.bars.order(“number_of_votes ASC”)

where I wanted the articles to show in the order of votes they received, but I wanted the ones with a nil number of votes to come last.

I found the answer in this Stack Overflow question using coalesce.

(1) First, I needed to determine the number of records (i.e. count = @foo.bars.count)

(2) Then I adjusted my code to:

count = @foo.bars.count

@bars = @foo.bars.order(“coalesce(number_of_votes, #{count}) ASC”)

This treated all of the nil values as if it had a number_of_votes, placing them at the end of the array.

Advertisements

Comments are closed.