Search code examples
ruby-on-railsransack

Ransack sort_link for SQL COUNT(), SUM and AVERAGE


I would like to add sort links for the following query:

@q = Order.group(:suburb).select("suburb, COUNT(*) as count, SUM(total) as total, AVG(total) as average").ransack(params[:q])

However when i use:

<%= sort_link(@q, :average) %>

The URL gets populated correctly, but no sorting is in place! When I inspect @q.sorts, the columns are correctly there.


Solution

  • There is no average column in database so it won't work like that. You could try hack this with ransacker:

    ransacker :average do
      Arel.sql('average')
    end
    

    so this average will be used when average is found.