使用Rails中的DataTable对格式化的日期列进行排序

问题描述 投票:0回答:1

如何按人类可读日期对DataTable进行排序?

一个常见问题是您希望用户看到的格式化日期未正确排序。

enter image description here

ruby-on-rails sorting date datatable iso8601
1个回答
0
投票

假设第一列是可排序的ISO日期,第二列是人类可读的格式化日期:

  %table.structures-list.stripe
    %thead
      %tr
        -# The ISO date column is for sorting
        %th Sortable
        %th Created
        %th Structure
        %th Area
    %tbody
      - items.each do |item|
        %tr.item{ id: dom_id(item.id) }
          -# The ISO date column is for sorting
          %td= item.created_at.iso8601
          %td= item.created_at.strftime("%d-%b-%Y")
          %td.ranked-name
            %a= link_to item.name, [item.preplan, item]
          %td= presenter.area

enter image description here

您可以在(haml)视图文件中按如下方式初始化DataTable:

:javascript
  $('.structures-list').DataTable({
    "order": [[ 0, "desc" ]],
    "pageLength": 25,
    // Have the created at column sorted by the ISO version
    "columnDefs": [
          { "targets": [1],
            "visible": true,
            "orderData": [0]
          },
          { "targets": [0],
            "visible": false
          }
    ]
  });

当您单击第二列上的排序箭头时,这将按第一列排序,并隐藏第一列。

enter image description here

(这是为了我未来的自我。)

© www.soinside.com 2019 - 2024. All rights reserved.