Ruby on rails 在CSV导出中容纳可变数量的字段

Ruby on rails 在CSV导出中容纳可变数量的字段,ruby-on-rails,ruby,csv,export,Ruby On Rails,Ruby,Csv,Export,我正在生成一个CSV导出(在ruby中,来自rails)的可变数量的记录。每个记录导出的字段数根据每本书的作者数量而有所不同。这并不理想,因为用户将在类似Excel的东西中查看此CSV,并希望看到列中一致显示的数据。如果csv生成器的结构如下所示,如何将列数设置为块被迭代的总次数: # header-row for the data csv << ["column heading 1", "column heading 2", "column heading 3" #etc] Bo

我正在生成一个CSV导出(在ruby中,来自rails)的可变数量的记录。每个记录导出的字段数根据每本书的作者数量而有所不同。这并不理想,因为用户将在类似Excel的东西中查看此CSV,并希望看到列中一致显示的数据。如果csv生成器的结构如下所示,如何将列数设置为块被迭代的总次数:

# header-row for the data
csv << ["column heading 1", "column heading 2", "column heading 3" #etc]

Book.all do |book|
  row_data = book.id
  row_data << book.some_other_field # etc
  book.authors.each do |author|
    row_data << author.first.name 
    #etc
#数据的标题行

csv更新:愚蠢的我误读了这个问题

我只会将标题的编写延迟一段时间。 Ruby能够将数据预挂起到文件中:

您只需携带作者的最大长度:

max_authors = 0    
Book.all do |book|
  row_data = book.id
  row_data << book.some_other_field # etc
  if book.authors.count > max_authors 
    max_authors = book.authors.count
  end
  book.authors.each do |author|
    row_data << author.first.name 
    #etc

# header-row for the data
a = (0..max_authors).collect { |n| "column heading #{n}" }
csv << a.join(",") #obviously this has to be prepended
max\u authors=0
读书。人人都读书|
行数据=book.id
行数据最大作者数
最大作者数=book.authors.count
结束
book.authors.each do | author|

哈哈,我从没想过!杰出的