简体   繁体   English

在视图中创建 Ruby on Rails 矩阵表

[英]Creating a Ruby on Rails Matrix Table in a view

I have records with the fields "year" and "month" and "value".我有字段“年”和“月”和“值”的记录。 What I'd like to do is to create a 12 column table corresponding with each "month" that displays the "value" in the "year" row.我想做的是创建一个与每个“月”相对应的 12 列表,在“年”行中显示“值”。 It seems like a pretty straightforward table to construct but I can't seem to get the view to display it properly.构建表格似乎非常简单,但我似乎无法让视图正确显示它。

I won't bother posting the code (yet) that I came up with already because nothing seems close to getting what I'm looking for.我不会费心发布我已经想出的代码(还),因为似乎没有什么能接近我正在寻找的东西。 I seems like this might be a pretty common thing to do with "group_by" but I have yet to see this type of example online.我似乎这可能是与“group_by”有关的很常见的事情,但我还没有在网上看到这种类型的例子。

here is the table details:这是表的详细信息:

create_table "returns", force: true do |t| 
  t.integer "year" 
  t.integer "month" 
  t.decimal "value" 
end

What is the best route to go about doing this?这样做的最佳途径是什么?

Here is an example how you can do it, this is not efficient way to do it but it is something you can improve:这是一个如何做到这一点的示例,这不是有效的方法,但您可以改进:

years = (2008..2015).to_a
months = (1..12).to_a

<table>
<tr>
    <td>Januray</td>
    ## .. rest of <td>'s of the month name
</td>
    years.each do |year|
      <tr>
        <td><%=year%></td>
        months.each do |month|
          <td><%= Return.where(year: year,month: month).first.try(:value) %></td>
        end
      </tr>
    end
</table>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM