Skip to content

Instantly share code, notes, and snippets.

@mathieugagne
Created April 30, 2014 00:36
Show Gist options
  • Save mathieugagne/27463cf3100a5ab44def to your computer and use it in GitHub Desktop.
Save mathieugagne/27463cf3100a5ab44def to your computer and use it in GitHub Desktop.
Sortable Headers
3 files to add sorting to table headers.
<th><%= sortable_header(:title) %></th>
<th><%= sortable_header(:description) %></th>
<th><%= sortable_header(:status) %></th>
<th><%= sortable_header(:comments_count, 'Comments') %></th>
def index
@projects = Project.order(sort_column => sort_direction)
end
private
def sort_column
Project.column_names.include?(params[:sort]) ? params[:sort] : "title"
end
helper_method :sort_column
def sort_direction
(['asc', 'desc'].include?(params[:direction]) ? params[:direction] : "asc").to_sym
end
helper_method :sort_direction
def sortable_header (column, title = nil)
title ||= column.titleize
css_class = column == sort_column ? "current #{sort_direction}" : nil
direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc"
link_to title, {sort: column, direction: direction}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment