I’m doing the Ryan Bates Sortable Table Columns screencast
If the item is inside a th tag and I want to apply a style if the item is selected how can I do it?
Ryan Screen Cast Code:
Controller
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
Helper
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
index.html.erb
<tr>
<th><%= sortable "name" %></th>
<th><%= sortable "price" %></th>
<th><%= sortable "released_at", "Released" %></th>
</tr>
concept
<tr>
<th class=<%= @selected %> ><%= sortable "name" %></th>
<th class=<%= @selected %> ><%= sortable "price" %></th>
<th class=<%= @selected %> ><%= sortable "released_at", "Released" %></th>
</tr>
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);
}
I’m not sure what really is the best convention, but I think something like this would work:
With an additional helper:
You can put some logic in there to determine what class to use based on the value of
selected. If you want no class, then usenil.I was inspired by this RailsCast:
http://railscasts.com/episodes/208-erb-blocks-in-rails-3
I hope it helps.