我在Ryan Bates教程之後實現了這個教程到sort table columns
,它的效果很好,但是當我渲染索引頁時,表已經按標題排序(asc),並且我只想在用戶點擊列標題。如何在rails中對錶格列進行排序?
我怎麼能做到這一點?
代碼
控制器
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_method
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>
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);
}
的你所描述的排序最好在Javascript中實現,因爲它從根本上說是一個客戶端問題(而rails有助於解決服務器端問題)。 jquery的表格分類器插件正是你想要的:http://tablesorter.com/docs/。 – Reck
嗨@Reck,謝謝你的推薦。作爲一個學習過程,我想探索使用rails做這件事的可能性。 – evanx
什麼是您想要的產品列表上的默認排序? –