Sorting Tables in Rails w/ Mongoid

Back | mongoid, rails, ruby | 10/13/2011 |

Sorting tables in Rails is a common problem. It must have been done before, right? In fact it has been done so many times that it’s really hard to find anything that “just works”.  Turned out to waste a lot of time of at least two people with creative libraries that fall short in many rather trivial ways. Of the good ones, a colleague tried sortable_table, but it’s not maintained and we finally settled on the much better handles_sortable_columns, which needed a tiny bit of integration work for Mongoid.

Lets make all our controllers support sorting with the sort_by parameter. Add the following to your ApplicationController.

  1. handles_sortable_columns do |conf|
  2.   conf.sort_param = "sort_by"
  3. end

This lets us add column sorting with sortable_column to a view (views/tags/index.html.haml).

  1. #tags
  2.   %table
  3.     %tr
  4.       %th= sortable_column "Name"
  5.       %th= sortable_column "Count"
  7.     - @tags.each do |tag|
  8.       %tr
  9. link_to h(, edit_tag_path(tag)
  10.         %td= tag.count

We can use sorting on a Mongoid model directly. For a Tag model, this means invoking Tag.desc(:field) or Tag.asc(:field) by name.

  1. sortable_column_order do |column, direction|
  2.   tags = Tag.send(direction, column)
  3. end

There’re several issues with this.

  1. We’ve just enabled parameter injection where one can send all kinds of wonderful queries into the Mongoid model by editing the URL.
  2. There’s no clear default sorting, for tags we’d like to sort by count in descending order.

The first issue can be solved by checking whether the direction is one of :asc or :desc and whether a column is a field in the model (added to config/initializers/mongoid_document.rb).

  1. module Mongoid
  2.   module Document
  3.     module ClassMethods
  4.       def sort_by(sort_column, sort_direction)
  5.         return nil unless ! sort_direction.blank? and [ :asc, :desc ].include?(sort_direction)
  6.         return nil unless ! sort_column.blank? and self.fields.has_key?(sort_column.to_s)
  7.         return self.send(sort_direction, sort_column)
  8.       end
  9.     end
  10.   end
  11. end

Since sort_by_column returns nil if no sorting has been done, we can use it to introduce a default sort in the Tags controller.

  1. class TagsController < ApplicationController
  2.   def index
  3.     sortable_column_order do |column, direction|
  4.         @tags = Tag.sort_by(column, direction)
  5.     end
  6.     @tags ||= Tag.desc(:count)
  7.     ...
  8.   end
  9.   ...
  10. end



I love the attention to detail with the little arrow next to the sorted column as well as the fact that this gem uses the –column syntax for sorting in descending order. It also properly supports pagination. Well done.