Over a million developers have joined DZone.

Sorting Tables in Rails with Mongoid

· Database Zone

Build fast, scale big with MongoDB Atlas, a hosted service for the leading NoSQL database. Try it now! Brought to you in partnership with MongoDB.

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.

    handles_sortable_columns do |conf|
      conf.sort_param = "sort_by"

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

          %th= sortable_column "Name"
          %th= sortable_column "Count"
        - @tags.each do |tag|
            %td.name= link_to h(tag.name), edit_tag_path(tag)
            %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.

    sortable_column_order do |column, direction|
      tags = Tag.send(direction, column)

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).

    module Mongoid
      module Document
        module ClassMethods
          def sort_by(sort_column, sort_direction)
            return nil unless ! sort_direction.blank? and [ :asc, :desc ].include?(sort_direction)
            return nil unless ! sort_column.blank? and self.fields.has_key?(sort_column.to_s)
            return self.send(sort_direction, sort_column)

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.

    class TagsController < ApplicationController
      def index
        sortable_column_order do |column, direction|
            @tags = Tag.sort_by(column, direction)
        @tags ||= Tag.desc(:count)



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.




Source: http://code.dblock.org/sorting-tables-in-rails-w-mongoid

Now it's easier than ever to get started with MongoDB, the database that allows startups and enterprises alike to rapidly build planet-scale apps. Introducing MongoDB Atlas, the official hosted service for the database on AWS. Try it now! Brought to you in partnership with MongoDB.


The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}