[英]Sortable table columns based on hash & key array
我想為我的表創建可排序的列,該列基於哈希將數據制成表格。 通過遵循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]]
在意見:-
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>
您可以使用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>
要還原排序順序,您還需要傳遞方向狀態,可能還需要傳遞逆序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.