Implementing Sortable Columns in Rails through Helper

Implementing Sortable Columns in Rails through Helper

< 1 Minute Read

Use of a sortable column in a listing view. For an example there is a list of “Programs”

Step# 1

  • Here our controller is named as “Programs” and the model is named as “Program”
  • Add the following helper methods to the controller
class ProgramsController < ApplicationController
helper_method :sort_column, :sort_direction
def sort_column
Program.column_names.include?(params[:sort]) ? params[:sort] : "position"
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
def your_custom_action

Step# 2

  • In Helper class of “Program” add the following codes
module ProgramsHelper
def sortable(column, title = nil)
title ||= column.titleize
active = column == sort_column
ascending = active && sort_direction == 'asc'
direction_html = ascending ? ' ▲ ' : ' ▼ ' if active
css_class = active ? "current #{sort_direction}" : nil
direction = ascending ? "desc" : "asc"
link_to(title, { :sort => column, :direction => direction }, :remote => true, :class => css_class) << raw(direction_html)


Step# 3

  • In the view (index.html.slim) file add the helper method “sortable” in the columns you want to sort
  • Please note: Here slim is used for the view pages
table style="text-align:left;"
th align="left" = sortable "name"
th align="left" = sortable "created_at", "Added"
th align="left" = sortable "subscription_level_id", "Subscription"
th align="left" = sortable "rating_average", "Rating"
- programs.each do |program|
= content_tag_for :tr, program, 'row_for' do
td= link_to, program_url(program)
td.attribute= program.created_at.strftime("%B %Y")
td.attribute= if program.subscription_level
td.attribute= ratings_for program
.pagination_container style="padding-bottom:20px;"
= will_paginate programs
Jayadev Das

Do what you do best in – that’s what I’ve always believed in and that’s what I preach. Over the past 25+ years (yup that’s my expertise ‘n’ experience in the Information Technology domain), I’ve been consulting to small, medium and large companies ‘bout Web Technologies, Mobile Future as well as on the good-and-bad of tech. Blogger, International Business Advisor, Web Technology Expert, Sales Guru, Startup Mentor, Insurance Sales Portal Expert & a Tennis Player. And top of all – a complete family man!