【问题标题】:Railscast #228 Sortable Table Columns: doesn't change a directionRailscast #228 可排序表列:不改变方向
【发布时间】:2015-10-15 11:37:36
【问题描述】:

我按照 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>

【问题讨论】:

  • 我认为您需要在 rails routs 中设置这些参数(位于 config/routes.rb 中)。
  • 你能举个例子吗?
  • 能否请您发布点击列名将您重定向到的页面的网址?
  • 试试这个:@posts = Post.all.paginate(:page =&gt; params[:page], :per_page =&gt; 4).order(id: :desc)

标签: ruby-on-rails sorting railscasts


【解决方案1】:

我不得不写:

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

代替:

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

【讨论】:

    猜你喜欢
    • 2011-04-23
    • 1970-01-01
    • 2021-11-02
    • 2020-07-03
    • 2015-08-18
    • 2012-12-15
    • 2017-11-03
    • 2011-01-08
    • 2021-10-05
    相关资源
    最近更新 更多