Я создал простой сортировщик таблиц:
ProductsController:
helper_method :sort_column, :sort_direction
# GET /products
# GET /products.xml
def index
@products = Product.order(sort_column+ " "+sort_direction)
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @products }
end
end
Application_helper
module ApplicationHelper
def sortable(column, title = nil )
title ||= column.titleize
direction = column == sort_column && sort_direction[:direction] == "asc" ? "desc" : "asc"
link_to title, {:sort => column, :direction => direction}
end
end
И просмотр:
<tr>
<th><%= sortable "name"%></th>
<th><%= sortable "price"%></th>
<th><%= sortable "released" %></th>
</tr>
После того, как я попытался открыть страницу / продукты, но я получил эту ошибку (Rails v 3.0.3):
can't convert Symbol into Integer
Extracted source (around line #5):
2:
3: <table>
4: <tr>
5: <th><%= sortable "name"%></th>
6: <th><%= sortable "price"%></th>
7: <th><%= sortable "released" %></th>
8: </tr>
И методы сортировки:
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