DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Data Engineering
  3. Databases
  4. Sorting Tables in Rails with Mongoid

Sorting Tables in Rails with Mongoid

Daniel Doubrovkine user avatar by
Daniel Doubrovkine
·
Jan. 22, 12 · Interview
Like (0)
Save
Tweet
Share
8.11K Views

Join the DZone community and get the full member experience.

Join For Free

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"
    end


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

    #tags
      %table
        %tr
          %th= sortable_column "Name"
          %th= sortable_column "Count"
     
        - @tags.each do |tag|
          %tr
            %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)
    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).

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

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


Screenshots

image


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.

image


Gem

  • https://github.com/dadooda/handles_sortable_column

 

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Java REST API Frameworks
  • Reliability Is Slowing You Down
  • Container Security: Don't Let Your Guard Down
  • Real-Time Analytics for IoT

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: