I have the hash, below:
library = {"1"=>{"title"=>"bbb", "money"=>10}, "2"=>{"title"=>"aaa", "money"=>12}}
and my application_helper.rb:
def sortable_columns
%w[title money]
end
def sort_column
sortable_columns.include?(params[:column]) ? params[:column] : "title"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
def sort_link(column, title)
direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc"
icon = sort_direction == "asc" ? "fa fa-arrow-down" : "fa fa-arrow-up"
icon = column == sort_column ? icon : ""
link_to "#{title} <i class='#{icon}'></i>".html_safe, {column: column, direction: direction}
end
My table in table.html.erb:
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<% sortable_columns.each do |column| %>
<th><%= sort_link column, column %></th>
<% end %>
</tr>
</thead>
<tbody>
<% library.sort_by {|k| k[1][sort_column]}.each_with_index do |data, i| %>
...
<% end %>
</tbody>
</table>
and now - after click in "title" or "money" header - table's sorting ASC. I would like it to display DESC when clicked again (with icon arrow-down). How can this be done? I thought about "reverse", after library.sort_by {|k| k[1][sort_column]}
, but doesn't work.