Railscast#228可排序表格列:不改变方向

时间:2015-10-15 11:37:37

标签: ruby-on-rails sorting railscasts

我按照Railscast的#228集在我的应用中创建了一个可排序的表格列。

我的问题:当我第一次按下列名时 - 它会按升序显示订单。下次我点击 - 它不会按降序自动显示记录;但是,如果我手动编写desc:" http://localhost:3000/admin/users/2/records?direction=desc&sort=created_at" - 它完美地运作;什么是问题?

我的控制器:

def records
    @records = @user.records.paginate(page: params[:page], per_page: 20).order(sort_column + " " + sort_direction)
  end

private
  def sort_column
    Record.column_names.include?(params[:sort]) ? params[:sort] : "created_at"
  end

  def sort_direction
    %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
  end

我的application_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

我的观点:

<tr>
  <th><%= sortable "created_at" %></th>
</tr>

1 个答案:

答案 0 :(得分:1)

我不得不写:

direction = sort_column && sort_direction == "asc" ? "desc" : "asc"

而不是:

direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc"