【问题标题】:Sortable table columns based on hash & key array基于哈希和键数组的可排序表列
【发布时间】:2016-06-15 03:10:31
【问题描述】:

我想为我的表创建可排序的列,该列根据哈希值对数据进行制表。关注http://railscasts.com/episodes/228-sortable-table-columns?view=asciicast。据我了解,order 方法只能用于整理模型。为此类表排序列的最佳方法是什么。如前所述,我有 29 个类似的表格。我的代码如下:-

admins_controller.rb

   class AdminsController < ApplicationController

     array =[]
     User.each do |user|
        company_name = Company.find(user.company_id).name
        array.push(company_name)
     end
     company = array.inject(Hash.new(0)) { |h, e| h[e] += 1 ; h }
   end

上述查询的结果如下所示:-

 array = [["3M", 4], ["A.P. Møller-Mærsk Group", 10], ["ABB", 14], ["Abbott Laboratories", 12]]

关于视图:-

admins.html.erb

    <table class="table">
    <tr>
      <th><%= link_to "Company", remote: true, :sort => "hash" %></th>
      <th><%= link_to "Value", remote: true, :sort => "key" %></th>
      <th><%= link_to "Percentage", remote: true, :sort => "Percentage"  %></th>
    </tr>
    <% if @mentors.try(:any?) %>
        <% @mentors.each do |key, value| %>
          <tr>
            <td><%= key %></td>
            <td><%= value  %> </td>
            <td><%= ((value.to_f/@total_co.to_f).to_f * 100 ).round(2)%> </td>
          </tr>
        <% end %>
    <% else %>
        <td> nil </td>
        <td> nil </td>
        <td> nil </td>
    <% end %> 
    </table>

【问题讨论】:

    标签: ruby-on-rails sorting dynamic hash html-table


    【解决方案1】:

    您可以选择 JavaScript / jQuery 解决方案,例如 http://tablesorter.com/docs/

    这将允许在前端进行排序,您无需调整后端。

    如果你想有一个后端解决方案,你可以去按列索引排序。一个简单的解决方案是这样的:

    控制器:

    class AdminsController < ApplicationController
      def index
        array =[]
        User.each do |user|
          company_name = Company.find(user.company_id).name
          array.push(company_name)
        end
    
        company = array.inject(Hash.new(0)) { |h, e| h[e] += 1 ; h }
    
        sort_column = params.fetch(:sort, 0).to_i
        company.sort! { |a, b| a[sort_column] <=> b[sort_column] }
      end
    end
    

    查看:

    <table class="table">
      <tr>
        <th><%= link_to "Company", remote: true, :sort => 0 %></th>
        <th><%= link_to "Value", remote: true, :sort => 1 %></th>
        <th><%= link_to "Percentage", remote: true, :sort => 1  %></th>
      </tr>
      <% if @mentors.try(:any?) %>
      <% @mentors.each do |key, value| %>
      <tr>
        <td><%= key %></td>
        <td><%= value  %> </td>
        <td><%= ((value.to_f/@total_co.to_f).to_f * 100 ).round(2)%> </td>
      </tr>
      <% end %>
      <% else %>
      <td> nil </td>
      <td> nil </td>
      <td> nil </td>
      <% end %>
    </table>
    

    为了恢复排序顺序,您还需要传递一个方向状态,并且可能是相反的顺序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-31
      • 1970-01-01
      • 2015-04-22
      • 2015-06-13
      • 1970-01-01
      • 2012-08-17
      • 2012-07-28
      • 1970-01-01
      相关资源
      最近更新 更多