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 protected def sort_column Program.column_names.include?(params[:sort]) ? params[:sort] : "position" end def sort_direction %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc" end def your_custom_action end end
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) end end
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
#main table style="text-align:left;" tr 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.name, program_url(program) td.attribute= program.created_at.strftime("%B %Y") td.attribute= program.subscription_level.name.capitalize if program.subscription_level td.attribute= ratings_for program .pagination_container style="padding-bottom:20px;" = will_paginate programs