我有一个Ruby on Rails页面,我试图在4列上设置可排序的标题。我使用http://railscasts.com/episodes/228-sortable-table-columns作为指南。我确定我错过了一些小的东西,但是排序完全在等级和输入的字段上工作,因为它们不在关联的表中。但是,当我尝试对用户和部门字段进行排序时,它只对升序进行排序。当我手动输入" desc"在网址中并发送该参数,但条件语句似乎不适用于员工和部门字段。此外,当我点击用户或部门标题时,它会显示" created_at"旁边的排序箭头,因此它似乎默认了辅助函数中的一些内容,但我无法找到原因它正在那样做。有人在代码中看到任何错误吗?
Index.html.erb
<table class="table table-striped table-hover">
<thead>
<tr>
<th><%= sortable "user", "Employee" %></th>
<th><%= sortable "dept", "Department" %></th>
<th><%= sortable "grade", "Grade" %></th>
<th><%= sortable "created_at", "Entered" %></th>
</tr>
</thead>
<tbody>
<% @transactions.each do |transaction| %>
<tr>
<td><%= link_to transaction.user.fl_name, transaction, :target => '_blank' %></td>
<td><%= transaction.user.department.name %></td>
<td><span class="<%= 'text-success bold' if transaction.grade >=
90 %>"><%= transaction.grade %></span></td>
<td><%= transaction.created_at.strftime("%b %d, %Y %l:%M %P") %></td>
</tr>
<% end %>
</tbody>
</table>
控制器
helper_method :sort_column, :sort_direction
def index
if (has_option("edit_option") == true) || (current_user.is_admin?)
if params[:sort] == "user"
@transactions = sort_by_user
elsif params[:sort] == "dept"
@transactions = sort_by_dept
else
@transactions = sort
end
respond_to do |format|
format.html # index.html.erb
format.json { render json: @transactions }
end
else
redirect_to root_path
end
end
def sort
transaction.order(sort_column + " " + sort_direction).page(params[:page])
end
def sort_by_user
transaction.paginate(
:page => params[:page],
:include => :user,
:order => "users.first_name #{sort_direction}")
end
def sort_by_dept
transaction.paginate(
:page => params[:page],
:include => :user,
:order => "users.department_name #{sort_direction}")
end
def sort_column
transaction.column_names.include?(params[:sort]) ? params[:sort] : "created_at"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "desc"
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
答案 0 :(得分:2)
direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc"
由于第一部分column == sort_column
,这种情况总是假的(同样适用于css_class
)。 sort_column
检查dept
/ user
是transaction.column_names
之一,因为它不是,它会返回默认created_at
,从而导致您的条件始终被评估为假并返回asc
。您所要做的就是更改sort_column
,因此它也适用于transaction.column_names
和user
/ dept
。或者只是
def sort_column
['user', 'dept', 'created_at', 'grade'].include?(params[:sort]) ? params[:sort] : "created_at
end
答案 1 :(得分:0)
在sort_column方法中看起来我需要这个,因为它没有找到用户表中的列:
def sort_column
(( Transaction.column_names.include?(params[:sort]) ) ||
( User.column_names.include?(params[:sort]) )) ? params[:sort] : "created_at"
end