#228 Sortable Table Columns
Here I walk you through adding the ability to sort table columns in ascending or descending order by clicking the header.
- Download:
- source codeProject Files in Zip (107 KB)
- mp4Full Size H.264 Video (17 MB)
- m4vSmaller H.264 Video (11.5 MB)
- webmFull Size VP8 Video (30.4 MB)
- ogvFull Size Theora Video (25.2 MB)
Resources
ruby
class ProductsController < ApplicationController
helper_method :sort_column, :sort_direction
def index
@products = Product.order(sort_column + " " + sort_direction)
end
# ...
private
def sort_column
Product.column_names.include?(params[:sort]) ? params[:sort] : "name"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
end
class ProductsController < ApplicationController helper_method :sort_column, :sort_direction def index @products = Product.order(sort_column + " " + sort_direction) end # ... private def sort_column Product.column_names.include?(params[:sort]) ? params[:sort] : "name" end def sort_direction %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc" end end
application_helper.rb
def sortable(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}, {:class => css_class}
end
def sortable(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}, {:class => css_class} end
products/index.html.erb
<tr>
<th><%= sortable "name" %></th>
<th><%= sortable "price" %></th>
<th><%= sortable "released_at", "Released" %></th>
</tr>
<tr> <th><%= sortable "name" %></th> <th><%= sortable "price" %></th> <th><%= sortable "released_at", "Released" %></th> </tr>
application.css
.pretty th .current {
padding-right: 12px;
background-repeat: no-repeat;
background-position: right center;
}
.pretty th .asc {
background-image: url(/images/up_arrow.gif);
}
.pretty th .desc {
background-image: url(/images/down_arrow.gif);
}
.pretty th .current { padding-right: 12px; background-repeat: no-repeat; background-position: right center; } .pretty th .asc { background-image: url(/images/up_arrow.gif); } .pretty th .desc { background-image: url(/images/down_arrow.gif); }

