2016-03-02 13 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> 

Для возвращаясь порядок сортировки, вам необходимо будет также передавать состояние направление и, возможно, в обратном порядке.