Ransack count sort order is wrong

I am using Ransack Gem and doing a count sort via counter cache. My attribute is an integer.

I am calling it like this:

<%= sort_link(@q, :people_count, "PEOPLE") %>

The sort output I am getting is:

[PEOPLE ASC]

1
2
0
0

[PEOPLE DESC]

0
0
2
1

I would like PEOPLE DESC to show:

2
1
0
0

Can anyone help out?

—UPDATE-----

After over an hour of searching I feel like I’m getting closer:

First I had to edit my view:

From

<%= mycontact.people.count %>

to

<%= mycontact.people_count %>

This changed all zeros to nil.

Now my sort output is:

[PEOPLE DESC]

nil
nil
2
1

Then I did some more digging and found the link to this issue on github which explains that you have to add NULLS LAST.

So I added the following code to peoples_controller.rb:

@q.result.except(:order).order("#{@q.sorts.first.attr_name} #{@q.sorts.first.dir} NULLS LAST")
I was excited at first because it worked but then after restarting my server am getting the following error:

undefined method `attr_name’ for nil:NilClass

@Gary_Riger Please try to track down the line of code and the object that is nil in the Ransack library.

I just put together this tip to help you do that.

Once you do that, post what you find.