将Ruby on Rails总和查询显示为数据透视表

时间:2019-03-06 10:04:24

标签: ruby-on-rails pivot-table

我有以下查询:

Customer.joins(:orders).group(:Category, :Year).sum(:Amount)

=> {["Category1", 2018]=>54, 
    ["Category1", 2019]=>187, 
    ["Category2", 2017]=>43,
    ["Category2", 2018]=>84,
    ["Category2", 2019]=>239}

我想在view.html.erb中将其作为数据透视表输出,如下所示:

Categories  |   2017   |  2018  |  2019  |
------------------------------------------
Category1   |          |  54    |  187   |
Category2   |   43     |  84    |  239   |

通常我可以做这样的事情,但这是不可能的:

<% @table.each do |r| %>
  <tr>
    <td><%= r.category %></td>
    <td><%= r.year %></td>
  </tr>

我该如何实现?

我已经有了这样的列名,但是我认为它太复杂了:

@table.uniq { |fields, data|  [fields[1]] }.each do |v|
  @table_column_names << v[0][1]

1 个答案:

答案 0 :(得分:0)

1 => lets say there is a hash x

x = {["Category1", 2018]=>54, 
    ["Category1", 2019]=>187, 
    ["Category2", 2017]=>43,
    ["Category2", 2018]=>84,
    ["Category2", 2019]=>239
}

2 => create a array [[category, year, count]...]

category_year_counts = []

x.each do |key, value|
  category_year_counts << [key[0], key[1], value]
end
#=>[["Category1", 2018, 54], ["Category1", 2019, 187], ["Category2", 2017, 43], ["Category2", 2018, 84], ["Category2", 2019, 239]] 

3 => Here it is -

<% x.each do |key, value| %>
  <tr>
    <td>categories</td>
    <%years = x.keys.map{|elm| elm[1]}.uniq%>
    <%years.each do |year|%>
      <td><%=year%></td>
    <%end%>
  <tr>
  <%categories_lists = x.keys.map{|elm| elm[0]}.uniq%>
  <%categories_lists.each do |category|%>
    <tr>
        <td><%=category%></td>
        <%years.each do |year|%>
           <%result= category_year_counts.select{|elm| elm[0].eql?(category) && elm[1].eql?(year)}.first%>
          <td><%=result.present? && result[2].present? ? result[2] : ""%></td>
        <%end%>     
    </tr>
  <%end%>
<%end%>

There may be more convenient way to do this.