bogdan / datagrid

Gem to create tables grids with sortable columns and filters
MIT License
1.02k stars 115 forks source link

Paginating when sorting by an aggregated value with :order_by_value option in column #255

Closed greenfork closed 5 years ago

greenfork commented 5 years ago

I'm trying to sort by an aggregated value from the association.

Here is the snippet:

column(:positions, order_by_value: true) do |model|
    model.positions.count
end

positions is an association for the model.

Everything works fine until I introduce pagination. I had to use this workaround:

# in controller
@clients_grid_assets = if @clients_grid.assets.is_a? Array
     total_count = @clients_grid.scope.limit(nil).offset(0).count
     Kaminari.paginate_array(@clients_grid.assets,
                                               total_count: total_count)
                    .page(params[:page])
     else
        @clients_grid.assets
     end

# in view
<%= paginate @clients_grid_assets %>

My problem is that when I use :order_by_value, the assets are converted into an array and I have to use Kaminari's paginate_array method. But the resulting assets seem to be already paginated by the datagrid gem.

The result is that I get sorting in the scope of a single page, meaning that the sorting is not applied to the whole dataset, only to the number of paginated results on the current page. How do I make the sorting to the whole dataset?

greenfork commented 5 years ago

I have solved this issue by using just order option and applying almost complete rewrite of the scope like so:

order: proc do
  scope.joins('LEFT JOIN smth').select('model.*, COUNT(*) as count_all').order('count_all')
end
kaydanzie commented 5 years ago

Is there really no other way to accomplish this without writing a custom order method?

greenfork commented 5 years ago

@kaylaziegler so far I have not found it. Custom order proc doesn't seem so bad though.