leikind / wice_grid

A Rails grid plugin to create grids with sorting, pagination, and (automatically generated) filters
MIT License
537 stars 215 forks source link

Sort by count of related record #178

Closed Flixt closed 9 years ago

Flixt commented 9 years ago

Hey,

I just wondered if there is a way to sort by a column that shows the count of a related model. I mean something like

  g.column name: 'Count', attribute: 'count(*)', :related_model => Visitor do |event|
    event.visitors.size
  end

I understood that the attributes are actual column names, but isn't that a good case of an exception. Or is it doable by custom sorting somehow? Thanks in advance.

Flixt commented 9 years ago

I didn't saw it is possible to pass ActiveRecordRelations to the initialize_grid method.

so the combination of

  def index
    @events_grid = initialize_grid(
      Event.select('events.*, COUNT(visitors.id) AS visitor_count').joins(:visitors).group('events.id'),
      custom_order: { 'visitors.event_id' => 'visitor_count' }
     )
  end

and

  g.column name: 'Count', model: Visitor, attribute: 'event_id' do |event|
    event.visitors.size
  end

works