哈希中的Sort_by-反转还是不反转-怎么做?

时间:2019-05-21 06:01:33

标签: ruby-on-rails ruby ruby-on-rails-5

我在下面有哈希值:

library = {"1"=>{"title"=>"bbb", "money"=>10}, "2"=>{"title"=>"aaa", "money"=>12}}

和我的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

我在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>

现在-单击“标题”或“金钱”标题后,表格的排序ASC。我希望它在再次单击时显示DESC(带有向下箭头的图标)。如何才能做到这一点?我在library.sort_by {|k| k[1][sort_column]}之后想到了“反向”,但是不起作用。

2 个答案:

答案 0 :(得分:0)

反向操作可以

library = {"1"=>{"title"=>"bbb", "money"=>10}, "2"=>{"title"=>"aaa", "money"=>12}}

sort_column = "money"

sort_direction = "asc"
library
  .sort_by {|k| k[1][sort_column]}
  .tap { |l| l.reverse! if sort_direction == "desc" }
# => [["1", {"title"=>"bbb", "money"=>10}], ["2", {"title"=>"aaa", "money"=>12}]]

sort_direction = "desc"
library
  .sort_by {|k| k[1][sort_column]}
  .tap { |l| l.reverse! if sort_direction == "desc" }
# => [["2", {"title"=>"aaa", "money"=>12}], ["1", {"title"=>"bbb", "money"=>10}]]

答案 1 :(得分:0)

您可以按照以下方式散列哈希值

如果仅按标题排序,则

library.values.sort_by{|h| h["title"] }

或者您要按首个标题和第二个货币排序,然后使用

library.values.sort_by{|h| [h["title"], h["money"]] }