Ransack count sort order is wrong
Asked Answered
D

1

8

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

Diaphane answered 26/1, 2015 at 13:50 Comment(2)
Gary, put in lots of print statements to figure out what the object is that's getting the nil. Don't hesitate to put in lots of prints statements in the Gems and to read the source code there. Helps tons!Micamicaela
github.com/activerecord-hackery/ransack/issues/443 maybe this can be helpfullCliff
B
0

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?

Biotope answered 7/2, 2015 at 17:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.