Gary Riger
Gary Riger

Reputation: 233

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

Upvotes: 8

Views: 1779

Answers (1)

Andrew Hendrie
Andrew Hendrie

Reputation: 6415

I'm not familiar with the Ransack gem; however, I may end up using it now that I've seen what it can do.

Try this:

<%= sort_link(@q, :people_count, "PEOPLE", default_order: :desc) if :people_count > 0 %>

Something along those lines should give you the following output for [PEOPLE DESC]:

2

1

Then you can do something like this:

<%= sort_link(@q, :people_count, "PEOPLE", default_order: :desc) where :people_count = 0 %>

To show the results with a count of 0.

Does this logic make sense?

Upvotes: 0

Related Questions