【问题标题】:Ruby CSV | How to skip few columns while reading CSV?红宝石 CSV |如何在阅读 CSV 时跳过几列?
【发布时间】:2016-12-22 16:54:39
【问题描述】:

我正在使用 Active record Import gem 将 CSV 文件中的数据批量导入数据库。但我想在导入时跳过几个 CSV 列。

例如,我的 xaa.csv 具有名称、作者、作者 ID、评级等标题。 导入时,我想跳过“author_id”列值并导入所有其他列。

books = CSV.read("/public/xaa.csv") //What more should I do here to skip the 3rd column
columns = [:name, :author, :rating]
Book.import columns, books, :validate => false

【问题讨论】:

  • 你试过什么?你有没有看过标题选项。阅读标题,然后您可以根据列有选择地导入每一行。我一直这样做
  • 试试这个columns = [:name, :author, nil, :rating]

标签: ruby-on-rails ruby activerecord activerecord-import


【解决方案1】:
books = []

CSV.foreach('/public/xaa.csv', headers: true) do |row|
  books << [row['name'], row['author'], row['rating']]
end

columns = [:name, :author, :rating]
Book.import(columns, books, validate: false)

【讨论】:

  • 这在功能上与原始代码没有什么不同。对于“如何跳过第 3 列”的要求,需要设置 row['rating'] = nil,或者将书籍中第 3 位的 nil 替换
  • 谢谢@vegetaras。
【解决方案2】:
books = CSV.readlines(path, headers:true).map{|row| row.values_at('name','rating') }

vegetaras 版本的内存效率略高。

【讨论】:

    猜你喜欢
    • 2014-02-22
    • 1970-01-01
    • 1970-01-01
    • 2013-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多