Ruby Array到HTML表,包括标题

时间:2013-04-25 21:11:11

标签: html ruby-on-rails arrays html-table

我正在尝试将我从CSV文本输入中解析的ruby数组数组作为HTML表格提供。

解析已将输入分离为具有相等列的行数组,从中创建了一个行数组数组。

Presentation需要适应行或列的任意组合,并将第一个数组(index = 0)视为表头。

这是在我的模型中:

class Size < ActiveRecord::Base

attr_accessor :chart_options, :test
attr_accessible :account_id, :chart, :name

belongs_to :account

def test
'<it>hello</it>'
end


def chart_options

require 'csv'   

@chart_options = CSV.parse(chart , {:headers => true, :col_sep => "|", :row_sep     => :auto, :skip_blanks => true})

@table = CSV.parse(chart, {:headers => true, :col_sep => "|", :row_sep => :auto, :skip_blanks => true}).to_a

@chart_options
@table

end

end

这是输出:

["UK ", " USA ", " Euro "]
["Small UK ", " Small US ", " Small Euro "]
["Med UK ", " Med US ", " Med Euro "]
["Large UK ", " Large US ", " Large Euro"]

更新的解决方案:

<table class="size_chart table table-striped">
    <thead>
        <tr>
          <% @headers.each do |header| %>
            <th><%= header %></th>
          <% end %>
        </tr>
    <thead>
    <tbody>
        <% @rows.each do |row| %>
          <tr>
            <% row.each do |column| %>
              <td><%= column %></td>
            <% end %>
            </tr>
          <% end %>
    </tbody>
</table>

1 个答案:

答案 0 :(得分:2)

<table>
<tr>
  <% @table.delete_at(0).each do |header| %>
    <th><%= header %></th>
  <% end %>
</tr>
<% @table.each do |row| %>
  <tr>
    <% row.each do |column| %>
      <td><%= column %></td>
    <% end %>
  <% end %>
</table>

警告:我没有测试过这段代码,所以可能会有拼写错误,但这是一般的想法,循环中的循环。

相关问题