我创建了一个简单的表格分类器:
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
答案 0 :(得分:4)
direction = column == sort_column && sort_direction[:direction] == "asc" ? "desc" : "asc"
应该改为这个。 sort_direction
看起来像是一个字符串,但你把它当成哈希。
direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc"