【问题标题】:Rails adding a row to a csv that only has headers and no data removes the headersRails 将一行添加到只有标题且没有数据的 csv 删除标题
【发布时间】:2020-09-16 19:06:56
【问题描述】:

我正在从 CDN 读取 CSV 文件并向其中添加数据,然后将其写回 CDN,因此我无法使用附加文件。

我也在重新排序文件,这就是为什么我必须将它转回 CSV::Table

此代码是我所拥有的代码的精简版本,但问题仍然存在。

class SomeForm::Form
  class << self

    def add
      data = CSV.parse(open(csv_file_url).read, headers: true)
      data << ['david', 'smith'] # this will be dynamic
      # data = data.sort_by { |row| [row['Firstname'], row['Lastname']] }
      write_csv_file(CSV::Table.new(data).to_csv)
    end


    def csv_file_url
      #somecode to get the file_url
    end

    def write_csv_file(data)
      #somecode to write the file to the cdn
    end
  end
end

CSV 文件

Firstname,Lastname

因此,如果我使用上面的 csv 文件运行 SomeForm::Form.add,它会输出(删除标题)

,
David,smith

但是,如果 CSV 文件在 eg 中至少有一条记录

Firstname,Lastname
Steve,Cougan

并按预期运行添加新记录的代码

Firstname,Lastname
Steve,Cougan
david,smith

我想让它与包含数据的 csv 和仅包含标题的 csv 一起使用。

顺便说一句,这是一个 rails3 项目,尽管上面的内容也可以在 rails 5 中复制

提前致谢

【问题讨论】:

    标签: ruby-on-rails csv ruby-on-rails-3


    【解决方案1】:

    我简化了脚本,但我无法真正重现您的问题。

    data = CSV.parse("Firstname,Lastname", headers: true)
    data << ['david', 'smith'] # this will be dynamic
    data = data.sort_by { |row| [row['Firstname'], row['Lastname']] }
    puts CSV::Table.new(data).to_csv
    
    # Firstname,Lastname
    # david,smith
    

    但是,如果您仍然遇到问题,我相信它可能是排序问题。 CSV::Table 类是可枚举的,但只迭代没有标题的 CSV 行(col 模式除外),这意味着您的排序可能只返回一个没有标题的数组数组。当您现在初始化新的CSV::Table 时,默认情况下它将使用第一行作为标题。请注意,您也可以像这样访问和设置标题。

    data = CSV.parse("Firstname,Lastname", headers: true)
    headers = data.headers
    
    data << ['david', 'smith'] # this will be dynamic
    data = data.sort_by { |row| [row['Firstname'], row['Lastname']] }
    
    puts CSV::Table.new(data, headers: headers).to_csv
    

    这里是实现的链接:

    【讨论】:

      【解决方案2】:

      我根据 Chrisians 的回答做了一些研究。

      认为这可能是问题https://github.com/ruby/csv/issues/75

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-02-21
        • 1970-01-01
        • 1970-01-01
        • 2020-04-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-11
        相关资源
        最近更新 更多