2016-03-02 116 views
0

我想爲我的表創建可排序的列,這些列根據散列製表數據。通過以下http://railscasts.com/episodes/228-sortable-table-columns?view=asciicast。據我所知,訂單方法只會工作整理一個模型。整理這些表格的列的最佳方法是什麼?我提到了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]] 

的看法: -

管理員.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> 

回答

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> 

對於恢復排序順序,你還需要通過一個方向狀態,可能顛倒順序。